From e4ff88f3640458f820838efd047a3831333446d8 Mon Sep 17 00:00:00 2001 From: c1570 Date: Mon, 22 Sep 2025 23:31:13 +0200 Subject: [PATCH 01/13] WIP improved docs (feat. LLM) --- docs/conf.py | 20 + docs/explanation/architecture.rst | 305 +++++++++++ docs/explanation/index.rst | 11 + docs/explanation/usb_concepts.rst | 352 +++++++++++++ docs/faq.rst | 210 ++++++++ docs/guides/index.rst | 10 + docs/guides/integration.rst | 494 ++++++++++++++++++ docs/index.rst | 64 ++- docs/reference/concurrency.rst | 10 +- docs/reference/configuration.rst | 296 +++++++++++ docs/reference/dependencies.rst | 2 +- docs/reference/glossary.rst | 89 ++++ docs/reference/index.rst | 12 +- docs/reference/usb_classes.rst | 290 ++++++++++ docs/troubleshooting.rst | 318 +++++++++++ docs/tutorials/first_device.rst | 147 ++++++ docs/tutorials/first_host.rst | 160 ++++++ .../getting_started.rst | 54 +- docs/tutorials/index.rst | 12 + 19 files changed, 2825 insertions(+), 31 deletions(-) create mode 100644 docs/explanation/architecture.rst create mode 100644 docs/explanation/index.rst create mode 100644 docs/explanation/usb_concepts.rst create mode 100644 docs/faq.rst create mode 100644 docs/guides/index.rst create mode 100644 docs/guides/integration.rst create mode 100644 docs/reference/configuration.rst create mode 100644 docs/reference/glossary.rst create mode 100644 docs/reference/usb_classes.rst create mode 100644 docs/troubleshooting.rst create mode 100644 docs/tutorials/first_device.rst create mode 100644 docs/tutorials/first_host.rst rename docs/{reference => tutorials}/getting_started.rst (73%) create mode 100644 docs/tutorials/index.rst 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'] diff --git a/docs/explanation/architecture.rst b/docs/explanation/architecture.rst new file mode 100644 index 000000000..4c63b198d --- /dev/null +++ b/docs/explanation/architecture.rst @@ -0,0 +1,305 @@ +************ +Architecture +************ + +This document explains TinyUSB's internal architecture, design principles, and how different components work together. + +Design Principles +================= + +Memory Safety +------------- + +TinyUSB is designed for resource-constrained embedded systems with strict memory requirements: + +- **No dynamic allocation**: All memory is statically allocated at compile time +- **Bounded buffers**: All buffers have compile-time defined sizes +- **Stack-based design**: No heap usage in the core stack +- **Predictable memory usage**: Memory consumption is deterministic + +Thread Safety +------------- + +TinyUSB achieves thread safety through a deferred interrupt model: + +- **ISR deferral**: USB interrupts are captured and deferred to task context +- **Single-threaded processing**: All USB protocol handling occurs in task context +- **Queue-based design**: Events are queued from ISR and processed in ``tud_task()`` +- **RTOS integration**: Proper semaphore/mutex usage for shared resources + +Portability +----------- + +The stack is designed to work across diverse microcontroller families: + +- **Hardware abstraction**: MCU-specific code isolated in portable drivers +- **OS abstraction**: RTOS dependencies isolated in OSAL layer +- **Modular design**: Features can be enabled/disabled at compile time +- **Standard compliance**: Strict adherence to USB specifications + +Core Architecture +================= + +Layer Structure +--------------- + +TinyUSB follows a layered architecture from hardware to application: + +.. code-block:: none + + ┌─────────────────────────────────────────┐ + │ 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. + +Device Stack Architecture +========================= + +Core Components +--------------- + +**Device Controller Driver (DCD)**: +- MCU-specific USB device peripheral driver +- Handles endpoint configuration and data transfers +- Abstracts hardware differences between MCU families +- Located in ``src/portable/VENDOR/FAMILY/`` + +**USB Device Core (USBD)**: +- Implements USB device state machine +- Handles standard USB requests (Chapter 9) +- Manages device configuration and enumeration +- Located in ``src/device/`` + +**Class Drivers**: +- Implement USB class specifications +- Handle class-specific requests and data transfer +- Provide application APIs +- Located in ``src/class/*/`` + +Data Flow +--------- + +**Control Transfers (Setup Requests)**: + +.. code-block:: none + + USB Bus → DCD → USBD Core → Class Driver → Application + ↓ + Standard requests handled in core + ↓ + Class-specific requests → Class Driver + +**Data Transfers**: + +.. code-block:: none + + Application → Class Driver → USBD Core → DCD → USB Bus + USB Bus → DCD → USBD Core → Class Driver → Application + +Event Processing +---------------- + +TinyUSB uses a deferred interrupt model for thread safety: + +1. **Interrupt Occurs**: USB hardware generates interrupt +2. **ISR Handler**: ``dcd_int_handler()`` captures event, minimal processing +3. **Event Queuing**: Events queued for later processing +4. **Task Processing**: ``tud_task()`` (called by application code) processes queued events +5. **Callback Execution**: Application callbacks executed in task context + +.. code-block:: none + + USB IRQ → ISR → Event Queue → tud_task() → Class Callbacks → Application + +Host Stack Architecture +======================= + +Core Components +--------------- + +**Host Controller Driver (HCD)**: +- MCU-specific USB host peripheral driver +- Manages USB pipes and data transfers +- Handles host controller hardware +- Located in ``src/portable/VENDOR/FAMILY/`` + +**USB Host Core (USBH)**: +- Implements USB host functionality +- Manages device enumeration and configuration +- Handles pipe management and scheduling +- Located in ``src/host/`` + +**Hub Driver**: +- Manages USB hub devices +- Handles port management and device detection +- Supports multi-level hub topologies +- Located in ``src/host/`` + +Device Enumeration +------------------ + +The host stack follows USB enumeration process: + +1. **Device Detection**: Hub or root hub detects device connection +2. **Reset and Address**: Reset device, assign unique address +3. **Descriptor Retrieval**: Get device, configuration, and class descriptors +4. **Driver Matching**: Find appropriate class driver for device +5. **Configuration**: Configure device and start communication +6. **Class Operation**: Normal class-specific communication + +.. code-block:: none + + Device Connect → Reset → Get Descriptors → Load Driver → Configure → Operate + +Class Architecture +================== + +Common Class Structure +---------------------- + +All USB classes follow a similar architecture: + +**Device Classes**: +- ``*_device.c``: Device-side implementation +- ``*_device.h``: Device API definitions +- Implement class-specific descriptors +- Handle class requests and data transfer + +**Host Classes**: +- ``*_host.c``: Host-side implementation +- ``*_host.h``: Host API definitions +- Manage connected devices of this class +- Provide application interface + +Class Driver Interface +---------------------- + +**Required Functions**: +- ``init()``: Initialize class driver +- ``reset()``: Reset class state +- ``open()``: Configure class endpoints +- ``control_xfer_cb()``: Handle control requests +- ``xfer_cb()``: Handle data transfer completion + +**Optional Functions**: +- ``close()``: Clean up class resources +- ``sof_cb()``: Start-of-frame processing + +Descriptor Management +--------------------- + +Each class is responsible for: +- **Interface Descriptors**: Define class type and endpoints +- **Class-Specific Descriptors**: Additional class requirements +- **Endpoint Descriptors**: Define data transfer characteristics + +Memory Management +================= + +Static Allocation Model +----------------------- + +TinyUSB uses only static memory allocation: + +- **Endpoint Buffers**: Fixed-size buffers for each endpoint +- **Class Buffers**: Static buffers for class-specific data +- **Control Buffers**: Fixed buffer for control transfers +- **Queue Buffers**: Static event queues + +Buffer Management +----------------- + +**Endpoint Buffers**: +- Allocated per endpoint at compile time +- Size defined by ``CFG_TUD_*_EP_BUFSIZE`` macros +- Used for USB data transfers + +**FIFO Buffers**: +- Ring buffers for streaming data +- Size defined by ``CFG_TUD_*_RX/TX_BUFSIZE`` macros +- Separate read/write pointers + +**DMA Considerations**: +- Buffers must be DMA-accessible on some MCUs +- Alignment requirements vary by hardware +- Cache coherency handled in portable drivers + +Threading Model +=============== + +Task-Based Design +----------------- + +TinyUSB uses a cooperative task model: + +- **Main Tasks**: ``tud_task()`` for device, ``tuh_task()`` for host +- **Regular Execution**: Tasks must be called regularly (< 1ms typical) +- **Event Processing**: All USB events processed in task context +- **Callback Execution**: Application callbacks run in task context + +RTOS Integration +---------------- + +**Bare Metal**: +- Application calls ``tud_task()`` in main loop +- No threading primitives needed +- Simplest integration method + +**FreeRTOS**: +- USB task runs at high priority +- Semaphores used for synchronization +- Queue for inter-task communication + +**Other RTOS**: +- Similar patterns with RTOS-specific primitives +- OSAL layer abstracts RTOS differences + +Interrupt Handling +------------------ + +**Interrupt Service Routine**: +- Minimal processing in ISR +- Event capture and queuing only +- Quick return to avoid blocking + +**Deferred Processing**: +- All complex processing in task context +- Thread-safe access to data structures +- Application callbacks in known context + +Memory Usage Patterns +--------------------- + +**Flash Memory**: +- Core stack: 8-15KB depending on features +- Each class: 1-4KB additional +- Portable driver: 2-8KB depending on MCU + +**RAM Usage**: +- Core stack: 1-2KB +- Endpoint buffers: User configurable +- Class buffers: Depends on configuration diff --git a/docs/explanation/index.rst b/docs/explanation/index.rst new file mode 100644 index 000000000..695efd9e0 --- /dev/null +++ b/docs/explanation/index.rst @@ -0,0 +1,11 @@ +*********** +Explanation +*********** + +Deep understanding of TinyUSB's design, architecture, and concepts. + +.. toctree:: + :maxdepth: 2 + + architecture + usb_concepts \ No newline at end of file diff --git a/docs/explanation/usb_concepts.rst b/docs/explanation/usb_concepts.rst new file mode 100644 index 000000000..02ba76770 --- /dev/null +++ b/docs/explanation/usb_concepts.rst @@ -0,0 +1,352 @@ +************ +USB Concepts +************ + +This document provides a brief introduction to USB protocol fundamentals that are essential for understanding TinyUSB development. + +USB Protocol Basics +==================== + +Universal Serial Bus (USB) is a standardized communication protocol designed for connecting devices to hosts (typically computers). Understanding these core concepts is essential for effective TinyUSB development. + +Host and Device Roles +---------------------- + +**USB Host**: The controlling side of a USB connection (typically a computer). The host: +- Initiates all communication +- Provides power to devices +- Manages the USB bus +- Enumerates and configures devices + +**TinyUSB Host Stack**: Enable with ``CFG_TUH_ENABLED=1`` in ``tusb_config.h``. Call ``tuh_task()`` regularly in your main loop. See :doc:`../tutorials/first_host` for implementation details. + +**USB Device**: The peripheral side (keyboard, mouse, storage device, etc.). Devices: +- Respond to host requests +- Cannot initiate communication +- Receive power from the host +- Must be enumerated by the host before use + +**TinyUSB Device Stack**: Enable with ``CFG_TUD_ENABLED=1`` in ``tusb_config.h``. Call ``tud_task()`` regularly in your main loop. See :doc:`../tutorials/first_device` for implementation details. + +**OTG (On-The-Go)**: Some devices can switch between host and device roles dynamically. **TinyUSB Support**: Both stacks can be enabled simultaneously on OTG-capable hardware. See ``examples/dual/`` for dual-role implementations. + +USB Transfers +============= + +Every USB transfer consists of the host issuing a request, and the device replying to that request. The host is the bus master and initiates all communication. +Devices cannot initiate sending data; for unsolicited incoming data, polling is used by the host. + +USB defines four transfer types, each intended for different use cases: + +Control Transfers +----------------- + +Used for device configuration and control commands. + +**Characteristics**: +- Bidirectional (uses both IN and OUT) +- Guaranteed delivery with error detection +- Limited data size (8-64 bytes per packet) +- All devices must support control transfers on endpoint 0 + +**Usage**: Device enumeration, configuration changes, class-specific commands + +**TinyUSB Context**: Handled automatically by the core stack for standard requests; class drivers handle class-specific requests. Endpoint 0 is managed by ``src/device/usbd.c`` and ``src/host/usbh.c``. Configure buffer size with ``CFG_TUD_ENDPOINT0_SIZE`` (typically 64 bytes). + +Bulk Transfers +-------------- + +Used for large amounts of data that don't require guaranteed timing. + +**Characteristics**: +- Unidirectional (separate IN and OUT endpoints) +- Guaranteed delivery with error detection +- Large packet sizes (up to 512 bytes for High Speed) +- Uses available bandwidth when no other transfers are active + +**Usage**: File transfers, large data communication, CDC serial data + +**TinyUSB Context**: Used by MSC (mass storage) and CDC classes for data transfer. Configure endpoint buffer sizes with ``CFG_TUD_MSC_EP_BUFSIZE`` and ``CFG_TUD_CDC_EP_BUFSIZE``. See ``src/class/msc/`` and ``src/class/cdc/`` for implementation details. + +Interrupt Transfers +------------------- + +Used for small, time-sensitive data with guaranteed maximum latency. + +**Characteristics**: +- Unidirectional (separate IN and OUT endpoints) +- Guaranteed delivery with error detection +- Small packet sizes (up to 64 bytes for Full Speed) +- Regular polling interval (1ms to 255ms) + +**Usage**: Keyboard/mouse input, sensor data, status updates + +**TinyUSB Context**: Used by HID class for input reports. Configure with ``CFG_TUD_HID`` and ``CFG_TUD_HID_EP_BUFSIZE``. Send reports using ``tud_hid_report()`` or ``tud_hid_keyboard_report()``. See ``src/class/hid/`` and HID examples in ``examples/device/hid_*/``. + +Isochronous Transfers +--------------------- + +Used for time-critical streaming data. + +**Characteristics**: +- Unidirectional (separate IN and OUT endpoints) +- No error correction (speed over reliability) +- Guaranteed bandwidth +- Real-time delivery + +**Usage**: Audio, video streaming + +**TinyUSB Context**: Used by Audio class for streaming audio data. Configure with ``CFG_TUD_AUDIO`` and related audio configuration macros. See ``src/class/audio/`` and audio examples in ``examples/device/audio_*/`` for UAC2 implementation. + +Endpoints and Addressing +========================= + +Endpoint Basics +--------------- + +**Endpoint**: A communication channel between host and device. + +- Each endpoint has a number (0-15) and direction +- Endpoint 0 is reserved for control transfers +- Other endpoints are assigned by device class requirements + +**TinyUSB Endpoint Management**: Configure maximum endpoints with ``CFG_TUD_ENDPOINT_MAX``. Endpoints are automatically allocated by enabled classes. See your board's ``usb_descriptors.c`` for endpoint assignments. + +**Direction**: +- **OUT**: Host to device (host sends data out) +- **IN**: Device to host (host reads data in) +- Note that in TinyUSB code, for ``tx``/``rx``, the device perspective is used typically: E.g., ``tud_cdc_tx_complete_cb()`` designates the callback executed once the device has completed sending data to the host (in device mode). + +**Addressing**: Endpoints are addressed as EPx IN/OUT (e.g., EP1 IN, EP2 OUT) + +Endpoint Configuration +---------------------- + +Each endpoint is configured with: +- **Transfer type**: Control, bulk, interrupt, or isochronous +- **Direction**: IN, OUT, or bidirectional (control only) +- **Maximum packet size**: Depends on USB speed and transfer type +- **Interval**: For interrupt and isochronous endpoints + +**TinyUSB Configuration**: Endpoint characteristics are defined in descriptors (``usb_descriptors.c``) and automatically configured by the stack. Buffer sizes are set via ``CFG_TUD_*_EP_BUFSIZE`` macros. + +Error Handling and Flow Control +------------------------------- + +**Transfer Results**: USB transfers can complete with different results: +- **ACK**: Successful transfer +- **NAK**: Device not ready (used for flow control) +- **STALL**: Error condition or unsupported request +- **Timeout**: Transfer failed to complete in time + +**Flow Control in USB**: Unlike network protocols, USB doesn't use congestion control. Instead: +- Devices use NAK responses when not ready to receive data +- Applications implement buffering and proper timing +- Some classes (like CDC) support hardware flow control (RTS/CTS) + +**TinyUSB Handling**: Transfer results are represented as ``xfer_result_t`` enum values. The stack automatically handles NAK responses and timing. STALL conditions indicate application-level errors that should be addressed in class drivers. + +USB Device States +================= + +A USB device progresses through several states: + +1. **Attached**: Device is physically connected +2. **Powered**: Device receives power from host +3. **Default**: Device responds to address 0 +4. **Address**: Device has been assigned a unique address +5. **Configured**: Device is ready for normal operation +6. **Suspended**: Device is in low-power state + +**TinyUSB State Management**: State transitions are handled automatically by ``src/device/usbd.c``. You can implement ``tud_mount_cb()`` and ``tud_umount_cb()`` to respond to configuration changes, and ``tud_suspend_cb()``/``tud_resume_cb()`` for power management. + +Device Enumeration Process +========================== + +When a device is connected, the host follows this process: + +1. **Detection**: Host detects device connection +2. **Reset**: Host resets the device +3. **Descriptor Requests**: Host requests device descriptors +4. **Address Assignment**: Host assigns unique address to device +5. **Configuration**: Host selects and configures device +6. **Class Loading**: Host loads appropriate drivers +7. **Normal Operation**: Device is ready for use + +**TinyUSB Role**: The device stack handles steps 1-6 automatically; your application handles step 7. + +USB Descriptors +=============== + +Descriptors are data structures that describe device capabilities: + +Device Descriptor +----------------- +Describes the device (VID, PID, USB version, etc.) + +Configuration Descriptor +------------------------ +Describes device configuration (power requirements, interfaces, etc.) + +Interface Descriptor +-------------------- +Describes a functional interface (class, endpoints, etc.) + +Endpoint Descriptor +------------------- +Describes endpoint characteristics (type, direction, size, etc.) + +String Descriptors +------------------ +Human-readable strings (manufacturer, product name, etc.) + +**TinyUSB Implementation**: You provide descriptors in ``usb_descriptors.c`` via callback functions: +- ``tud_descriptor_device_cb()`` - Device descriptor +- ``tud_descriptor_configuration_cb()`` - Configuration descriptor +- ``tud_descriptor_string_cb()`` - String descriptors + +The stack automatically handles descriptor requests during enumeration. See examples in ``examples/device/*/usb_descriptors.c`` for reference implementations. + +USB Classes +=========== + +USB classes define standardized protocols for device types: + +**Class Code**: Identifies the device type in descriptors +**Class Driver**: Software that implements the class protocol +**Class Requests**: Standardized commands for the class + +**Common TinyUSB-Supported Classes**: +- **CDC (02h)**: Communication devices (virtual serial ports) - Enable with ``CFG_TUD_CDC`` +- **HID (03h)**: Human interface devices (keyboards, mice) - Enable with ``CFG_TUD_HID`` +- **MSC (08h)**: Mass storage devices (USB drives) - Enable with ``CFG_TUD_MSC`` +- **Audio (01h)**: Audio devices (speakers, microphones) - Enable with ``CFG_TUD_AUDIO`` +- **MIDI**: MIDI devices - Enable with ``CFG_TUD_MIDI`` +- **DFU**: Device Firmware Update - Enable with ``CFG_TUD_DFU`` +- **Vendor**: Custom vendor classes - Enable with ``CFG_TUD_VENDOR`` + +See :doc:`../reference/usb_classes` for detailed class information and :doc:`../reference/configuration` for configuration options. + +USB Speeds +========== + +USB supports multiple speed modes: + +**Low Speed (1.5 Mbps)**: +- Simple devices (mice, keyboards) +- Limited endpoint types and sizes + +**Full Speed (12 Mbps)**: +- Most common for embedded devices +- All transfer types supported +- Maximum packet sizes: Control (64), Bulk (64), Interrupt (64) + +**High Speed (480 Mbps)**: +- High-performance devices +- Larger packet sizes: Control (64), Bulk (512), Interrupt (1024) +- Requires more complex hardware + +**Super Speed (5 Gbps)**: +- USB 3.0 and later +- Not supported by TinyUSB + +**TinyUSB Speed Support**: Most TinyUSB ports support Full Speed and High Speed. Speed is typically auto-detected by hardware. Configure speed requirements in board configuration (``hw/bsp/FAMILY/boards/BOARD/board.mk``) and ensure your MCU supports the desired speed. + +USB Device Controllers +====================== + +USB device controllers are hardware peripherals that handle the low-level USB protocol implementation. Understanding how they work helps explain TinyUSB's architecture and portability. + +Controller Fundamentals +----------------------- + +**What Controllers Do**: +- Handle USB signaling and protocol timing +- Manage endpoint buffers and data transfers +- Generate interrupts for USB events +- Implement USB electrical specifications + +**Key Components**: +- **Physical Layer**: USB signal drivers and receivers +- **Protocol Engine**: Handles USB packets, ACK/NAK responses +- **Endpoint Buffers**: Hardware FIFOs or RAM for data storage +- **Interrupt Controller**: Generates events for software processing + +Controller Architecture Types +----------------------------- + +Different MCU vendors implement USB controllers with varying architectures. +To list a few common patterns: + +**FIFO-Based Controllers** (e.g., STM32 OTG, NXP LPC): +- Shared or dedicated FIFOs for endpoint data +- Software manages FIFO allocation and data flow +- Common in higher-end MCUs with flexible configurations + +**Buffer-Based Controllers** (e.g., STM32 FSDEV, Microchip SAMD, RP2040): +- Fixed packet memory areas for each endpoint +- Hardware automatically handles packet placement +- Simpler programming model, common in smaller MCUs + +**Descriptor-Based Controllers** (e.g., NXP EHCI-style): +- Use descriptor chains to describe transfers +- Hardware processes transfer descriptors independently +- More complex but can handle larger transfers autonomously + +TinyUSB Controller Abstraction +------------------------------ + +TinyUSB abstracts controller differences through the TinyUSB **Device Controller Driver (DCD)** layer. +These internal details don't matter to users of TinyUSB typically; however, when debugging, knowledge about internal details helps sometimes. + +**Portable Interface** (``src/device/usbd.h``): +- Standardized function signatures for all controllers +- Common endpoint and transfer management APIs +- Unified interrupt and event handling + +**Controller-Specific Drivers** (``src/portable/VENDOR/FAMILY/``): +- Implement the DCD interface for specific hardware +- Handle vendor-specific register layouts and behaviors +- Manage controller-specific quirks and workarounds + +**Common DCD Functions**: +- ``dcd_init()`` - Initialize controller hardware +- ``dcd_edpt_open()`` - Configure endpoint with type and size +- ``dcd_edpt_xfer()`` - Start data transfer on endpoint +- ``dcd_int_handler()`` - Process USB interrupts +- ``dcd_connect()/dcd_disconnect()`` - Control USB bus connection + +Controller Event Flow +--------------------- + +**Typical USB Event Processing**: + +1. **Hardware Event**: USB controller detects bus activity (setup packet, data transfer, etc.) +2. **Interrupt Generation**: Controller generates interrupt to CPU +3. **ISR Processing**: ``dcd_int_handler()`` reads controller status +4. **Event Queuing**: Events are queued for later processing (thread safety) +5. **Task Processing**: ``tud_task()`` processes queued events +6. **Class Notification**: Appropriate class drivers handle the event +7. **Application Callback**: User code responds to the event + +Power Management +================ + +USB provides power to devices: + +**Bus-Powered**: Device draws power from USB bus (up to 500mA) +**Self-Powered**: Device has its own power source +**Suspend/Resume**: Devices must enter low-power mode when bus is idle + +**TinyUSB Power Management**: +- Implement ``tud_suspend_cb()`` and ``tud_resume_cb()`` for power management +- Configure power requirements in device descriptor (``bMaxPower`` field) +- Use ``tud_remote_wakeup()`` to wake the host from suspend (if supported) +- Enable remote wakeup with ``CFG_TUD_USBD_ENABLE_REMOTE_WAKEUP`` + +Next Steps +========== + +- Start with :doc:`../tutorials/getting_started` for basic setup +- Review :doc:`../reference/configuration` for configuration options +- Check :doc:`../guides/integration` for advanced integration scenarios diff --git a/docs/faq.rst b/docs/faq.rst new file mode 100644 index 000000000..ede97032d --- /dev/null +++ b/docs/faq.rst @@ -0,0 +1,210 @@ +************************** +Frequently Asked Questions +************************** + +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. + +**Q: Can I use TinyUSB in commercial projects?** + +Yes, TinyUSB is released under the MIT license, allowing commercial use with minimal restrictions. + +**Q: Does TinyUSB require an RTOS?** + +No, TinyUSB works in bare metal environments. It also supports FreeRTOS, RT-Thread, and Mynewt. + +**Q: How much memory does TinyUSB use?** + +Typical usage: 8-20KB flash, 1-4KB RAM depending on enabled classes and configuration. The stack uses static allocation only. + +Build and Setup +================ + +**Q: Why do I get "arm-none-eabi-gcc: command not found"?** + +Install the ARM GCC toolchain: ``sudo apt-get install gcc-arm-none-eabi`` on Ubuntu/Debian, or download from ARM's website for other platforms. + +**Q: Build fails with "Board 'X' not found"** + +Check available boards: ``ls hw/bsp/FAMILY/boards/`` or run ``python tools/build.py -l`` to list all supported boards. + +**Q: What are the dependencies and how do I get them?** + +Run ``python tools/get_deps.py FAMILY`` where FAMILY is your MCU family (e.g., stm32f4, rp2040). This downloads MCU-specific drivers and libraries. + +**Q: Can I use my own build system instead of Make/CMake?** + +Yes, just add all ``.c`` files from ``src/`` to your project and configure include paths. See :doc:`guides/integration` for details. + +**Q: Error: "tusb_config.h: No such file or directory"** + +This is a very common issue. You need to create ``tusb_config.h`` in your project and ensure it's in your include path. The file must define ``CFG_TUSB_MCU`` and ``CFG_TUSB_OS`` at minimum. Copy from ``examples/device/*/tusb_config.h`` as a starting point. + +**Q: RP2040 + pico-sdk ignores my tusb_config.h settings** + +The pico-sdk build system can override ``tusb_config.h`` settings. The ``CFG_TUSB_OS`` setting is often ignored because pico-sdk sets it to ``OPT_OS_PICO`` internally. Use pico-sdk specific configuration methods or modify the CMake configuration. + +**Q: "multiple definition of dcd_..." errors with STM32** + +This happens when multiple USB drivers are included. Ensure you're only including the correct portable driver for your STM32 family. Check that ``CFG_TUSB_MCU`` is set correctly and you don't have conflicting source files. + +Device Development +================== + +**Q: My USB device isn't recognized by the host** + +Common causes: +- Invalid USB descriptors - validate with ``LOG=2`` build +- ``tud_task()`` not called regularly in main loop +- Incorrect ``tusb_config.h`` settings +- USB cable doesn't support data (charging-only cable) + +**Q: Windows shows "Device Descriptor Request Failed"** + +This typically indicates: +- Malformed device descriptor +- USB timing issues (check crystal/clock configuration) +- Power supply problems during enumeration +- Conflicting devices on the same USB hub + +**Q: How do I implement a custom USB class?** + +Use the vendor class interface (``CFG_TUD_VENDOR``) or implement a custom class driver. See ``src/class/vendor/`` for examples. + +**Q: Can I have multiple configurations or interfaces?** + +Yes, TinyUSB supports multiple configurations and composite devices. Modify the descriptors in ``usb_descriptors.c`` accordingly. + +**Q: How do I change Vendor ID/Product ID?** + +Edit the device descriptor in ``usb_descriptors.c``. For production, obtain your own VID from USB-IF or use one from your silicon vendor. + +**Q: Device works alone but fails when connected through USB hub** + +This is a known issue where some devices interfere with each other when connected to the same hub. Try: +- Using different USB hubs +- Connecting devices to separate USB ports +- Checking for power supply issues with the hub + +Host Development +================ + +**Q: Why doesn't my host application detect any devices?** + +Check: +- Power supply - host mode requires more power than device mode +- USB connector type - use USB-A for host applications +- Board supports host mode on the selected port +- Enable logging with ``LOG=2`` to see enumeration details + +**Q: Can I connect multiple devices simultaneously?** + +Yes, through a USB hub. TinyUSB supports multi-level hubs and multiple device connections. + +**Q: Does TinyUSB support USB 3.0?** + +No, TinyUSB currently supports USB 2.0 and earlier. USB 3.0 devices typically work in USB 2.0 compatibility mode. + +Configuration and Features +========================== + +**Q: How do I enable/disable specific USB classes?** + +Edit ``tusb_config.h`` and set the corresponding ``CFG_TUD_*`` or ``CFG_TUH_*`` macros to 1 (enable) or 0 (disable). + +**Q: Can I use both device and host modes simultaneously?** + +Yes, with dual-role/OTG capable hardware. See ``examples/dual/`` for implementation examples. + +**Q: How do I optimize for code size?** + +- Disable unused classes in ``tusb_config.h`` +- Use ``CFG_TUSB_DEBUG = 0`` for release builds +- Compile with ``-Os`` optimization +- Consider using only required endpoints/interfaces + +**Q: Does TinyUSB support low power/suspend modes?** + +Yes, TinyUSB handles USB suspend/resume. Implement ``tud_suspend_cb()`` and ``tud_resume_cb()`` for custom power management. + +**Q: What CFG_TUSB_MCU should I use for x86/PC platforms?** + +For PC/motherboard applications, there's no standard MCU option. You may need to use a generic option or modify TinyUSB for your specific use case. Consider using libusb or other PC-specific USB libraries instead. + +**Q: RP2040 FreeRTOS configuration issues** + +The RP2040 pico-sdk has specific requirements for FreeRTOS integration. The ``CFG_TUSB_OS`` setting may be overridden by the SDK. Use pico-sdk specific configuration methods and ensure proper task stack sizes for the USB task. + +Debugging and Troubleshooting +============================= + +**Q: How do I debug USB communication issues?** + +1. Enable logging: build with ``LOG=2`` +2. Use ``LOGGER=rtt`` or ``LOGGER=swo`` for high-speed logging +3. Use USB protocol analyzers for detailed traffic analysis +4. Check with different host systems (Windows/Linux/macOS) + +**Q: My application crashes or hard faults** + +Common causes: +- Stack overflow - increase stack size in linker script +- Incorrect interrupt configuration +- Buffer overruns in USB callbacks +- Build with ``DEBUG=1`` and use a debugger + +**Q: Performance is poor or USB transfers are slow** + +- Ensure ``tud_task()``/``tuh_task()`` called frequently (< 1ms intervals) +- Use DMA for USB transfers if supported by your MCU +- Optimize endpoint buffer sizes +- Consider using high-speed USB if available + +**Q: Some USB devices don't work with my host application** + +- Not all devices follow USB standards perfectly +- Some may need device-specific handling +- Composite devices may have partial support +- Check device descriptors and implement custom drivers if needed + +**Q: ESP32-S3 USB host/device issues** + +ESP32-S3 has specific USB implementation challenges: +- Ensure proper USB pin configuration +- 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/guides/index.rst b/docs/guides/index.rst new file mode 100644 index 000000000..cad3dd27f --- /dev/null +++ b/docs/guides/index.rst @@ -0,0 +1,10 @@ +********** +How-to Guides +********** + +Problem-solving guides for common TinyUSB development tasks. + +.. toctree:: + :maxdepth: 2 + + integration \ No newline at end of file diff --git a/docs/guides/integration.rst b/docs/guides/integration.rst new file mode 100644 index 000000000..c135c5ec6 --- /dev/null +++ b/docs/guides/integration.rst @@ -0,0 +1,494 @@ +********************* +Integration Guide +********************* + +This guide covers integrating TinyUSB into production projects with your own build system, custom hardware, and specific requirements. + +Project Integration Methods +============================ + +Method 1: Git Submodule (Recommended) +-------------------------------------- + +Best for projects using git version control. + +.. code-block:: bash + + # Add TinyUSB as submodule + git submodule add https://github.com/hathach/tinyusb.git lib/tinyusb + git submodule update --init --recursive + +**Advantages:** +- Pinned to specific TinyUSB version +- Easy to update with ``git submodule update`` +- Version control tracks exact TinyUSB commit + +Method 2: Package Manager Integration +------------------------------------- + +**PlatformIO:** + +.. code-block:: ini + + ; platformio.ini + [env:myboard] + platform = your_platform + board = your_board + framework = arduino ; or other framework + lib_deps = + https://github.com/hathach/tinyusb.git + +**CMake FetchContent:** + +.. code-block:: cmake + + include(FetchContent) + FetchContent_Declare( + tinyusb + GIT_REPOSITORY https://github.com/hathach/tinyusb.git + GIT_TAG master # or specific version tag + ) + FetchContent_MakeAvailable(tinyusb) + +Method 3: Direct Copy +--------------------- + +Copy TinyUSB source files directly into your project. + +.. code-block:: bash + + # Copy only source files + cp -r tinyusb/src/ your_project/lib/tinyusb/ + +**Note:** You'll need to manually update when TinyUSB releases new versions. + +Build System Integration +======================== + +Make/GCC Integration +-------------------- + +**Makefile example:** + +.. code-block:: make + + # TinyUSB settings + TUSB_DIR = lib/tinyusb + TUSB_SRC_DIR = $(TUSB_DIR)/src + + # Include paths + CFLAGS += -I$(TUSB_SRC_DIR) + CFLAGS += -I. # For tusb_config.h + + # MCU and OS settings (pass to compiler) + CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_STM32F4 + CFLAGS += -DCFG_TUSB_OS=OPT_OS_NONE + + # TinyUSB source files + SRC_C += $(wildcard $(TUSB_SRC_DIR)/*.c) + SRC_C += $(wildcard $(TUSB_SRC_DIR)/common/*.c) + SRC_C += $(wildcard $(TUSB_SRC_DIR)/device/*.c) + SRC_C += $(wildcard $(TUSB_SRC_DIR)/class/*/*.c) + SRC_C += $(wildcard $(TUSB_SRC_DIR)/portable/$(VENDOR)/$(CHIP_FAMILY)/*.c) + +**Finding the right portable driver:** + +.. code-block:: bash + + # List available drivers + find lib/tinyusb/src/portable -name "*.c" | grep stm32 + # Use: lib/tinyusb/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c + +CMake Integration +----------------- + +**CMakeLists.txt example:** + +.. code-block:: cmake + + # TinyUSB configuration + set(FAMILY_MCUS STM32F4) # Set your MCU family + set(CFG_TUSB_MCU OPT_MCU_STM32F4) + set(CFG_TUSB_OS OPT_OS_FREERTOS) # or OPT_OS_NONE + + # Add TinyUSB + add_subdirectory(lib/tinyusb) + + # Your project + add_executable(your_app + src/main.c + src/usb_descriptors.c + # other sources + ) + + # Link TinyUSB + target_link_libraries(your_app + tinyusb_device # or tinyusb_host + # other libraries + ) + + # Include paths + target_include_directories(your_app PRIVATE + src/ # For tusb_config.h + ) + + # Compile definitions + target_compile_definitions(your_app PRIVATE + CFG_TUSB_MCU=${CFG_TUSB_MCU} + CFG_TUSB_OS=${CFG_TUSB_OS} + ) + +IAR Embedded Workbench +---------------------- + +Use project connection files for easy integration: + +1. Open IAR project +2. Add TinyUSB project connection: ``Tools → Configure Custom Argument Variables`` +3. Create ``TUSB`` group, add ``TUSB_DIR`` variable +4. Import ``tinyusb/tools/iar_template.ipcf`` + +Keil µVision +------------ + +.. code-block:: none + + # Add to project groups: + TinyUSB/Common: src/common/*.c + TinyUSB/Device: src/device/*.c, src/class/*/*.c + TinyUSB/Portable: src/portable/vendor/family/*.c + + # Include paths: + src/ # tusb_config.h location + lib/tinyusb/src/ + + # Preprocessor defines: + CFG_TUSB_MCU=OPT_MCU_STM32F4 + CFG_TUSB_OS=OPT_OS_NONE + +Configuration Setup +=================== + +Create tusb_config.h +-------------------- + +This is the most critical file for TinyUSB integration: + +.. code-block:: c + + // tusb_config.h + #ifndef _TUSB_CONFIG_H_ + #define _TUSB_CONFIG_H_ + + // MCU selection - REQUIRED + #ifndef CFG_TUSB_MCU + #define CFG_TUSB_MCU OPT_MCU_STM32F4 + #endif + + // OS selection - REQUIRED + #ifndef CFG_TUSB_OS + #define CFG_TUSB_OS OPT_OS_NONE + #endif + + // Debug level + #define CFG_TUSB_DEBUG 0 + + // Device stack + #define CFG_TUD_ENABLED 1 + #define CFG_TUD_ENDPOINT0_SIZE 64 + + // Device classes + #define CFG_TUD_CDC 1 + #define CFG_TUD_HID 0 + #define CFG_TUD_MSC 0 + + // CDC configuration + #define CFG_TUD_CDC_EP_BUFSIZE 512 + #define CFG_TUD_CDC_RX_BUFSIZE 512 + #define CFG_TUD_CDC_TX_BUFSIZE 512 + + #endif + +USB Descriptors +--------------- + +Create or modify ``usb_descriptors.c`` for your device: + +.. code-block:: c + + #include "tusb.h" + + // Device descriptor + tusb_desc_device_t const desc_device = { + .bLength = sizeof(tusb_desc_device_t), + .bDescriptorType = TUSB_DESC_DEVICE, + .bcdUSB = 0x0200, + .bDeviceClass = TUSB_CLASS_MISC, + .bDeviceSubClass = MISC_SUBCLASS_COMMON, + .bDeviceProtocol = MISC_PROTOCOL_IAD, + .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE, + .idVendor = 0xCafe, // Your VID + .idProduct = 0x4000, // Your PID + .bcdDevice = 0x0100, + .iManufacturer = 0x01, + .iProduct = 0x02, + .iSerialNumber = 0x03, + .bNumConfigurations = 0x01 + }; + + // Get device descriptor + uint8_t const* tud_descriptor_device_cb(void) { + return (uint8_t const*)&desc_device; + } + + // Configuration descriptor - implement based on your needs + uint8_t const* tud_descriptor_configuration_cb(uint8_t index) { + // Return configuration descriptor + } + + // String descriptors + uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + // Return string descriptors + } + +Application Integration +====================== + +Main Loop Integration +-------------------- + +.. code-block:: c + + #include "tusb.h" + + int main(void) { + // Board/MCU initialization + board_init(); // Your board setup + + // USB stack initialization + tusb_init(); + + while (1) { + // USB device task - MUST be called regularly + tud_task(); + + // Your application code + your_app_task(); + } + } + +Interrupt Handler Setup +----------------------- + +**STM32 example:** + +.. code-block:: c + + // USB interrupt handler + void OTG_FS_IRQHandler(void) { + tud_int_handler(0); + } + +**RP2040 example:** + +.. code-block:: c + + void isr_usbctrl(void) { + tud_int_handler(0); + } + +Class Implementation +-------------------- + +Implement required callbacks for enabled classes: + +.. code-block:: c + + // CDC class callbacks + void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding) { + // Handle line coding changes + } + + void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) { + // Handle DTR/RTS changes + } + +RTOS Integration +=============== + +FreeRTOS Integration +------------------- + +.. code-block:: c + + // USB task + void usb_device_task(void* param) { + while (1) { + tud_task(); + vTaskDelay(1); // 1ms delay + } + } + + // Create USB task + xTaskCreate(usb_device_task, "usbd", + 256, NULL, configMAX_PRIORITIES-1, NULL); + +**Configuration:** + +.. code-block:: c + + // In tusb_config.h + #define CFG_TUSB_OS OPT_OS_FREERTOS + #define CFG_TUD_TASK_QUEUE_SZ 16 + +RT-Thread Integration +-------------------- + +.. code-block:: c + + // In tusb_config.h + #define CFG_TUSB_OS OPT_OS_RTTHREAD + + // USB thread + void usb_thread_entry(void* parameter) { + tusb_init(); + while (1) { + tud_task(); + rt_thread_mdelay(1); + } + } + +Custom Hardware Integration +=========================== + +Clock Configuration +------------------- + +USB requires precise 48MHz clock: + +**STM32 example:** + +.. code-block:: c + + // Configure PLL for 48MHz USB clock + RCC_OscInitStruct.PLL.PLLQ = 7; // Adjust for 48MHz + HAL_RCC_OscConfig(&RCC_OscInitStruct); + +**RP2040 example:** + +.. code-block:: c + + // USB clock is automatically configured by SDK + +Pin Configuration +----------------- + +Configure USB pins correctly: + +**STM32 example:** + +.. code-block:: c + + // USB pins: PA11 (DM), PA12 (DP) + GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + +Power Management +--------------- + +For battery-powered applications: + +.. code-block:: c + + // Implement suspend/resume callbacks + void tud_suspend_cb(bool remote_wakeup_en) { + // Enter low power mode + } + + void tud_resume_cb(void) { + // Exit low power mode + } + +Testing and Validation +====================== + +Build Verification +------------------ + +.. code-block:: bash + + # Test build + make clean && make all + + # Check binary size + arm-none-eabi-size build/firmware.elf + + # Verify no undefined symbols + arm-none-eabi-nm build/firmware.elf | grep " U " + +Runtime Testing +--------------- + +1. **Device Recognition**: Check if device appears in system +2. **Enumeration**: Verify all descriptors are valid +3. **Class Functionality**: Test class-specific features +4. **Performance**: Measure transfer rates and latency +5. **Stress Testing**: Long-running tests with connect/disconnect + +Debugging Integration Issues +============================ + +Common Problems +--------------- + +1. **Device not recognized**: Check descriptors and configuration +2. **Build errors**: Verify include paths and source files +3. **Link errors**: Check library dependencies +4. **Runtime crashes**: Enable debug builds and use debugger +5. **Poor performance**: Profile code and optimize critical paths + +Debug Builds +------------ + +.. code-block:: c + + // In tusb_config.h for debugging + #define CFG_TUSB_DEBUG 2 + #define CFG_TUSB_DEBUG_PRINTF printf + +Enable logging to identify issues quickly. + +Production Considerations +========================= + +Code Size Optimization +---------------------- + +.. code-block:: c + + // Minimal configuration + #define CFG_TUSB_DEBUG 0 + #define CFG_TUD_CDC 1 + #define CFG_TUD_HID 0 + #define CFG_TUD_MSC 0 + // Disable unused classes + +Performance Optimization +------------------------ + +- Use DMA for USB transfers if available +- Optimize descriptor sizes +- Use appropriate endpoint buffer sizes +- Consider high-speed USB for high bandwidth applications + +Compliance and Certification +---------------------------- + +- Validate descriptors against USB specifications +- Test with USB-IF compliance tools +- Consider USB-IF certification for commercial products +- Test with multiple host operating systems \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst index c1c8e4d99..9fbc5bd30 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,14 +1,64 @@ -:hide-toc: +TinyUSB Documentation +===================== -.. include:: ../README_processed.rst +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:`tutorials/getting_started` +* Need to solve a specific problem? Check :doc:`guides/index` +* Looking for API details? See :doc:`reference/index` +* Want to understand the design? Read :doc:`explanation/architecture` +* Having issues? Check :doc:`faq` and :doc:`troubleshooting` + +Documentation Structure +----------------------- .. toctree:: - :caption: Index - :hidden: + :maxdepth: 2 + :caption: Learning - Info - Reference - Contributing + tutorials/index + +.. toctree:: + :maxdepth: 2 + :caption: Problem Solving + + guides/index + faq + troubleshooting + +.. toctree:: + :maxdepth: 2 + :caption: Information + + reference/index + +.. toctree:: + :maxdepth: 2 + :caption: Understanding + + explanation/index + +.. toctree:: + :maxdepth: 1 + :caption: Project Info + + info/index + contributing/index .. toctree:: :caption: External Links diff --git a/docs/reference/concurrency.rst b/docs/reference/concurrency.rst index 776fa4b6d..99e7e7b70 100644 --- a/docs/reference/concurrency.rst +++ b/docs/reference/concurrency.rst @@ -3,17 +3,17 @@ Concurrency *********** The TinyUSB library is designed to operate on single-core MCUs with multi-threaded applications in mind. Interaction with interrupts is especially important to pay attention to. -It is compatible with optionally using a RTOS. +It is compatible with optionally using an RTOS. General ------- -When writing code, keep in mind that the OS (if using a RTOS) may swap out your code at any time. Also, your code can be preempted by an interrupt at any time. +When writing code, keep in mind that the OS (if using an RTOS) may swap out your code at any time. Also, your code can be preempted by an interrupt at any time. Application Code ---------------- -The USB core does not execute application callbacks while in an interrupt context. Calls to application code are from within the USB core task context. Note that the application core will call class drivers from within their own task. +The USB core does not execute application callbacks while in an interrupt context. Calls to application code are from within the USB core task context. Note that the application core will call class drivers from within its own task. Class Drivers ------------- @@ -38,5 +38,5 @@ Much of the processing of the USB stack is done in an interrupt context, and car In particular: -* Ensure that all memory-mapped registers (including packet memory) are marked as volatile. GCC's optimizer will even combine memory access (like two 16-bit to be a 32-bit) if you don't mark the pointers as volatile. On some architectures, this can use macros like _I , _O , or _IO. -* All defined global variables are marked as ``static``. +* Ensure that all memory-mapped registers (including packet memory) are marked as volatile. GCC's optimizer will even combine memory accesses (like two 16-bit to be a 32-bit) if you don't mark the pointers as volatile. On some architectures, this can use macros like _I , _O , or _IO. +* All defined global variables are marked as ``static``. diff --git a/docs/reference/configuration.rst b/docs/reference/configuration.rst new file mode 100644 index 000000000..8d6dd6190 --- /dev/null +++ b/docs/reference/configuration.rst @@ -0,0 +1,296 @@ +************* +Configuration +************* + +TinyUSB behavior is controlled through compile-time configuration in ``tusb_config.h``. This reference covers all available configuration options. + +Basic Configuration +=================== + +Required Settings +----------------- + +.. code-block:: c + + // Target MCU family - REQUIRED + #define CFG_TUSB_MCU OPT_MCU_STM32F4 + + // OS abstraction layer - REQUIRED + #define CFG_TUSB_OS OPT_OS_NONE + + // Enable device or host stack + #define CFG_TUD_ENABLED 1 // Device stack + #define CFG_TUH_ENABLED 1 // Host stack + +Debug and Logging +----------------- + +.. code-block:: c + + // Debug level (0=off, 1=error, 2=warning, 3=info) + #define CFG_TUSB_DEBUG 2 + + // Memory alignment for buffers (usually 4) + #define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4))) + +Device Stack Configuration +========================== + +Endpoint Configuration +---------------------- + +.. code-block:: c + + // Control endpoint buffer size + #define CFG_TUD_ENDPOINT0_SIZE 64 + + // Number of endpoints (excluding EP0) + #define CFG_TUD_ENDPOINT_MAX 16 + +Device Classes +-------------- + +**CDC (Communication Device Class)**: + +.. code-block:: c + + #define CFG_TUD_CDC 1 // Number of CDC interfaces + #define CFG_TUD_CDC_EP_BUFSIZE 512 // CDC endpoint buffer size + #define CFG_TUD_CDC_RX_BUFSIZE 256 // CDC RX FIFO size + #define CFG_TUD_CDC_TX_BUFSIZE 256 // CDC TX FIFO size + +**HID (Human Interface Device)**: + +.. code-block:: c + + #define CFG_TUD_HID 1 // Number of HID interfaces + #define CFG_TUD_HID_EP_BUFSIZE 16 // HID endpoint buffer size + +**MSC (Mass Storage Class)**: + +.. code-block:: c + + #define CFG_TUD_MSC 1 // Number of MSC interfaces + #define CFG_TUD_MSC_EP_BUFSIZE 512 // MSC endpoint buffer size + +**Audio Class**: + +.. code-block:: c + + #define CFG_TUD_AUDIO 1 // Number of audio interfaces + #define CFG_TUD_AUDIO_FUNC_1_DESC_LEN 220 + #define CFG_TUD_AUDIO_FUNC_1_N_AS_INT 1 + #define CFG_TUD_AUDIO_FUNC_1_CTRL_BUF_SZ 64 + #define CFG_TUD_AUDIO_ENABLE_EP_IN 1 + #define CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_TX 2 + #define CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX 2 + +**MIDI**: + +.. code-block:: c + + #define CFG_TUD_MIDI 1 // Number of MIDI interfaces + #define CFG_TUD_MIDI_RX_BUFSIZE 128 // MIDI RX buffer size + #define CFG_TUD_MIDI_TX_BUFSIZE 128 // MIDI TX buffer size + +**DFU (Device Firmware Update)**: + +.. code-block:: c + + #define CFG_TUD_DFU 1 // Enable DFU mode + #define CFG_TUD_DFU_XFER_BUFSIZE 512 // DFU transfer buffer size + +**Vendor Class**: + +.. code-block:: c + + #define CFG_TUD_VENDOR 1 // Number of vendor interfaces + #define CFG_TUD_VENDOR_EPSIZE 64 // Vendor endpoint size + +Host Stack Configuration +======================== + +Port and Hub Configuration +-------------------------- + +.. code-block:: c + + // Number of host root hub ports + #define CFG_TUH_HUB 1 + + // Number of connected devices (including hub) + #define CFG_TUH_DEVICE_MAX 5 + + // Control transfer buffer size + #define CFG_TUH_ENUMERATION_BUFSIZE 512 + +Host Classes +------------ + +**CDC Host**: + +.. code-block:: c + + #define CFG_TUH_CDC 2 // Number of CDC host instances + #define CFG_TUH_CDC_FTDI 1 // FTDI serial support + #define CFG_TUH_CDC_CP210X 1 // CP210x serial support + #define CFG_TUH_CDC_CH34X 1 // CH34x serial support + +**HID Host**: + +.. code-block:: c + + #define CFG_TUH_HID 4 // Number of HID instances + #define CFG_TUH_HID_EPIN_BUFSIZE 64 // HID endpoint buffer size + #define CFG_TUH_HID_EPOUT_BUFSIZE 64 + +**MSC Host**: + +.. code-block:: c + + #define CFG_TUH_MSC 1 // Number of MSC instances + #define CFG_TUH_MSC_MAXLUN 4 // Max LUNs per device + +Advanced Configuration +====================== + +Memory Management +----------------- + +.. code-block:: c + + // Enable stack protection + #define CFG_TUSB_DEBUG_PRINTF printf + + // Custom memory allocation (if needed) + #define CFG_TUSB_MEM_SECTION __attribute__((section(".usb_ram"))) + +RTOS Configuration +------------------ + +**FreeRTOS**: + +.. code-block:: c + + #define CFG_TUSB_OS OPT_OS_FREERTOS + #define CFG_TUD_TASK_QUEUE_SZ 16 + #define CFG_TUH_TASK_QUEUE_SZ 16 + +**RT-Thread**: + +.. code-block:: c + + #define CFG_TUSB_OS OPT_OS_RTTHREAD + +Low Power Configuration +----------------------- + +.. code-block:: c + + // Enable remote wakeup + #define CFG_TUD_USBD_ENABLE_REMOTE_WAKEUP 1 + + // Suspend/resume callbacks + // Implement tud_suspend_cb() and tud_resume_cb() + +MCU-Specific Options +==================== + +The ``CFG_TUSB_MCU`` option selects the target microcontroller family: + +.. code-block:: c + + // STM32 families + #define CFG_TUSB_MCU OPT_MCU_STM32F0 + #define CFG_TUSB_MCU OPT_MCU_STM32F1 + #define CFG_TUSB_MCU OPT_MCU_STM32F4 + #define CFG_TUSB_MCU OPT_MCU_STM32F7 + #define CFG_TUSB_MCU OPT_MCU_STM32H7 + + // NXP families + #define CFG_TUSB_MCU OPT_MCU_LPC18XX + #define CFG_TUSB_MCU OPT_MCU_LPC40XX + #define CFG_TUSB_MCU OPT_MCU_LPC43XX + #define CFG_TUSB_MCU OPT_MCU_KINETIS_KL + #define CFG_TUSB_MCU OPT_MCU_IMXRT + + // Other vendors + #define CFG_TUSB_MCU OPT_MCU_RP2040 + #define CFG_TUSB_MCU OPT_MCU_ESP32S2 + #define CFG_TUSB_MCU OPT_MCU_ESP32S3 + #define CFG_TUSB_MCU OPT_MCU_SAMD21 + #define CFG_TUSB_MCU OPT_MCU_SAMD51 + #define CFG_TUSB_MCU OPT_MCU_NRF5X + +Configuration Examples +====================== + +Minimal Device (CDC only) +-------------------------- + +.. code-block:: c + + #define CFG_TUSB_MCU OPT_MCU_STM32F4 + #define CFG_TUSB_OS OPT_OS_NONE + #define CFG_TUSB_DEBUG 0 + + #define CFG_TUD_ENABLED 1 + #define CFG_TUD_ENDPOINT0_SIZE 64 + + #define CFG_TUD_CDC 1 + #define CFG_TUD_CDC_EP_BUFSIZE 512 + #define CFG_TUD_CDC_RX_BUFSIZE 512 + #define CFG_TUD_CDC_TX_BUFSIZE 512 + + // Disable other classes + #define CFG_TUD_HID 0 + #define CFG_TUD_MSC 0 + #define CFG_TUD_MIDI 0 + #define CFG_TUD_AUDIO 0 + #define CFG_TUD_VENDOR 0 + +Full-Featured Host +------------------ + +.. code-block:: c + + #define CFG_TUSB_MCU OPT_MCU_STM32F4 + #define CFG_TUSB_OS OPT_OS_FREERTOS + #define CFG_TUSB_DEBUG 2 + + #define CFG_TUH_ENABLED 1 + #define CFG_TUH_HUB 1 + #define CFG_TUH_DEVICE_MAX 8 + #define CFG_TUH_ENUMERATION_BUFSIZE 512 + + #define CFG_TUH_CDC 2 + #define CFG_TUH_HID 4 + #define CFG_TUH_MSC 2 + #define CFG_TUH_VENDOR 2 + +Validation +========== + +Use these checks to validate your configuration: + +.. code-block:: c + + // In your main.c, add compile-time checks + #if !defined(CFG_TUSB_MCU) || (CFG_TUSB_MCU == OPT_MCU_NONE) + #error "CFG_TUSB_MCU must be defined" + #endif + + #if CFG_TUD_ENABLED && !defined(CFG_TUD_ENDPOINT0_SIZE) + #error "CFG_TUD_ENDPOINT0_SIZE must be defined for device stack" + #endif + +Common Configuration Issues +=========================== + +1. **Endpoint buffer size too small**: Causes transfer failures +2. **Missing CFG_TUSB_MCU**: Build will fail +3. **Incorrect OS setting**: RTOS functions won't work properly +4. **Insufficient endpoint count**: Device enumeration will fail +5. **Buffer size mismatches**: Data corruption or transfer failures + +For configuration examples specific to your board, check ``examples/device/*/tusb_config.h``. \ No newline at end of file diff --git a/docs/reference/dependencies.rst b/docs/reference/dependencies.rst index 9ca9b0b54..e04cc2c2f 100644 --- a/docs/reference/dependencies.rst +++ b/docs/reference/dependencies.rst @@ -2,7 +2,7 @@ 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 ======================================== ================================================================ ======================================== ====================================================================================================================================================================================================================================================================================================================================================================== Local Path Repo Commit Required by diff --git a/docs/reference/glossary.rst b/docs/reference/glossary.rst new file mode 100644 index 000000000..e6e92738f --- /dev/null +++ b/docs/reference/glossary.rst @@ -0,0 +1,89 @@ +******** +Glossary +******** + +.. glossary:: + + Bulk Transfer + USB transfer type used for large amounts of data that doesn't require guaranteed timing. Used by mass storage devices and CDC class. + + CDC + Communications Device Class. USB class for devices that communicate serial data, creating virtual serial ports. + + Control Transfer + USB transfer type used for device configuration and control. All USB devices must support control transfers on endpoint 0. + + DCD + Device Controller Driver. The hardware abstraction layer for USB device controllers in TinyUSB. + + Descriptor + Data structures that describe USB device capabilities, configuration, and interfaces to the host. + + Device Class + USB specification defining how devices of a particular type (e.g., storage, audio, HID) communicate with hosts. + + DFU + Device Firmware Update. USB class that allows firmware updates over USB. + + Endpoint + Communication channel between host and device. Each endpoint has a direction (IN/OUT) and transfer type. + + Enumeration + Process where USB host discovers and configures a newly connected device. + + HCD + Host Controller Driver. The hardware abstraction layer for USB host controllers in TinyUSB. + + HID + Human Interface Device. USB class for input devices like keyboards, mice, and game controllers. + + High Speed + USB 2.0 speed mode operating at 480 Mbps. + + Full Speed + USB speed mode operating at 12 Mbps, supported by USB 1.1 and 2.0. + + Low Speed + USB speed mode operating at 1.5 Mbps, typically used by simple input devices. + + Interrupt Transfer + USB transfer type for small, time-sensitive data with guaranteed maximum latency. + + Isochronous Transfer + USB transfer type for time-critical data like audio/video with guaranteed bandwidth but no error correction. + + MSC + Mass Storage Class. USB class for storage devices like USB drives. + + OSAL + Operating System Abstraction Layer. TinyUSB component that abstracts RTOS differences. + + OTG + On-The-Go. USB specification allowing devices to act as both host and device. + + Pipe + Host-side communication channel to a device endpoint. + + Root Hub + The USB hub built into the host controller, where devices connect directly. + + Stall + USB protocol mechanism where an endpoint responds with a STALL handshake to indicate an error condition or unsupported request. Used for error handling, not flow control. + + Super Speed + USB 3.0 speed mode operating at 5 Gbps. Not supported by TinyUSB. + + UAC + USB Audio Class. USB class for audio devices. + + UVC + USB Video Class. USB class for video devices like cameras. + + VID + Vendor Identifier. 16-bit number assigned by USB-IF to identify device manufacturers. + + PID + 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 diff --git a/docs/reference/index.rst b/docs/reference/index.rst index 8ac3cf924..cb35dd1b9 100644 --- a/docs/reference/index.rst +++ b/docs/reference/index.rst @@ -1,10 +1,16 @@ -Index -===== +********* +Reference +********* + +Complete reference documentation for TinyUSB APIs, configuration, and supported hardware. .. toctree:: :maxdepth: 2 - getting_started + api/index + configuration + usb_classes boards dependencies concurrency + glossary diff --git a/docs/reference/usb_classes.rst b/docs/reference/usb_classes.rst new file mode 100644 index 000000000..00a251ffb --- /dev/null +++ b/docs/reference/usb_classes.rst @@ -0,0 +1,290 @@ +*********** +USB Classes +*********** + +TinyUSB supports multiple USB device and host classes. This reference describes the features, capabilities, and requirements for each class. + +Device Classes +============== + +CDC (Communication Device Class) +-------------------------------- + +Implements USB CDC specification for serial communication. + +**Supported Features:** +- CDC-ACM (Abstract Control Model) for virtual serial ports +- Data terminal ready (DTR) and request to send (RTS) control lines +- Line coding configuration (baud rate, parity, stop bits) +- Break signal support + +**Configuration:** +- ``CFG_TUD_CDC``: Number of CDC interfaces (1-4) +- ``CFG_TUD_CDC_EP_BUFSIZE``: Endpoint buffer size (typically 512) +- ``CFG_TUD_CDC_RX_BUFSIZE``: Receive FIFO size +- ``CFG_TUD_CDC_TX_BUFSIZE``: Transmit FIFO size + +**Key Functions:** +- ``tud_cdc_available()``: Check bytes available to read +- ``tud_cdc_read()``: Read data from host +- ``tud_cdc_write()``: Write data to host +- ``tud_cdc_write_flush()``: Flush transmit buffer + +**Callbacks:** +- ``tud_cdc_line_coding_cb()``: Line coding changed +- ``tud_cdc_line_state_cb()``: DTR/RTS state changed + +HID (Human Interface Device) +---------------------------- + +Implements USB HID specification for input devices. + +**Supported Features:** +- Boot protocol (keyboard/mouse) +- Report protocol with custom descriptors +- Input, output, and feature reports +- Multiple HID interfaces + +**Configuration:** +- ``CFG_TUD_HID``: Number of HID interfaces +- ``CFG_TUD_HID_EP_BUFSIZE``: Endpoint buffer size + +**Key Functions:** +- ``tud_hid_ready()``: Check if ready to send report +- ``tud_hid_report()``: Send HID report +- ``tud_hid_keyboard_report()``: Send keyboard report +- ``tud_hid_mouse_report()``: Send mouse report + +**Callbacks:** +- ``tud_hid_descriptor_report_cb()``: Provide report descriptor +- ``tud_hid_get_report_cb()``: Handle get report request +- ``tud_hid_set_report_cb()``: Handle set report request + +MSC (Mass Storage Class) +------------------------ + +Implements USB mass storage for file systems. + +**Supported Features:** +- SCSI transparent command set +- Multiple logical units (LUNs) +- Read/write operations +- Inquiry and capacity commands + +**Configuration:** +- ``CFG_TUD_MSC``: Number of MSC interfaces +- ``CFG_TUD_MSC_EP_BUFSIZE``: Endpoint buffer size + +**Key Functions:** +- Storage operations handled via callbacks + +**Required Callbacks:** +- ``tud_msc_inquiry_cb()``: Device inquiry information +- ``tud_msc_test_unit_ready_cb()``: Test if LUN is ready +- ``tud_msc_capacity_cb()``: Get LUN capacity +- ``tud_msc_start_stop_cb()``: Start/stop LUN +- ``tud_msc_read10_cb()``: Read data from LUN +- ``tud_msc_write10_cb()``: Write data to LUN + +Audio Class +----------- + +Implements USB Audio Class 2.0 specification. + +**Supported Features:** +- Audio streaming (input/output) +- Multiple sampling rates +- Volume and mute controls +- Feedback endpoints for asynchronous mode + +**Configuration:** +- ``CFG_TUD_AUDIO``: Number of audio functions +- Multiple configuration options for channels, sample rates, bit depth + +**Key Functions:** +- ``tud_audio_read()``: Read audio data +- ``tud_audio_write()``: Write audio data +- ``tud_audio_clear_ep_out_ff()``: Clear output FIFO + +MIDI +---- + +Implements USB MIDI specification. + +**Supported Features:** +- MIDI 1.0 message format +- Multiple virtual MIDI cables +- Standard MIDI messages + +**Configuration:** +- ``CFG_TUD_MIDI``: Number of MIDI interfaces +- ``CFG_TUD_MIDI_RX_BUFSIZE``: Receive buffer size +- ``CFG_TUD_MIDI_TX_BUFSIZE``: Transmit buffer size + +**Key Functions:** +- ``tud_midi_available()``: Check available MIDI messages +- ``tud_midi_read()``: Read MIDI packet +- ``tud_midi_write()``: Send MIDI packet + +DFU (Device Firmware Update) +---------------------------- + +Implements USB DFU specification for firmware updates. + +**Supported Modes:** +- DFU Mode: Device enters DFU for firmware update +- DFU Runtime: Request transition to DFU mode + +**Configuration:** +- ``CFG_TUD_DFU``: Enable DFU mode +- ``CFG_TUD_DFU_RUNTIME``: Enable DFU runtime + +**Key Functions:** +- Firmware update operations handled via callbacks + +**Required Callbacks:** +- ``tud_dfu_download_cb()``: Receive firmware data +- ``tud_dfu_manifest_cb()``: Complete firmware update + +Vendor Class +------------ + +Custom vendor-specific USB class implementation. + +**Features:** +- Configurable endpoints +- Custom protocol implementation +- WebUSB support +- Microsoft OS descriptors + +**Configuration:** +- ``CFG_TUD_VENDOR``: Number of vendor interfaces +- ``CFG_TUD_VENDOR_EPSIZE``: Endpoint size + +**Key Functions:** +- ``tud_vendor_available()``: Check available data +- ``tud_vendor_read()``: Read vendor data +- ``tud_vendor_write()``: Write vendor data + +Host Classes +============ + +CDC Host +-------- + +Connect to CDC devices (virtual serial ports). + +**Supported Devices:** +- CDC-ACM devices +- FTDI USB-to-serial converters +- CP210x USB-to-serial converters +- CH34x USB-to-serial converters + +**Configuration:** +- ``CFG_TUH_CDC``: Number of CDC host instances +- ``CFG_TUH_CDC_FTDI``: Enable FTDI support +- ``CFG_TUH_CDC_CP210X``: Enable CP210x support + +**Key Functions:** +- ``tuh_cdc_available()``: Check available data +- ``tuh_cdc_read()``: Read from CDC device +- ``tuh_cdc_write()``: Write to CDC device +- ``tuh_cdc_set_baudrate()``: Configure serial settings + +HID Host +-------- + +Connect to HID devices (keyboards, mice, etc.). + +**Supported Devices:** +- Boot keyboards and mice +- Generic HID devices with report descriptors +- Composite HID devices + +**Configuration:** +- ``CFG_TUH_HID``: Number of HID host instances +- ``CFG_TUH_HID_EPIN_BUFSIZE``: Input endpoint buffer size + +**Key Functions:** +- ``tuh_hid_receive_report()``: Start receiving reports +- ``tuh_hid_send_report()``: Send report to device +- ``tuh_hid_parse_report_descriptor()``: Parse HID descriptors + +MSC Host +-------- + +Connect to mass storage devices (USB drives). + +**Supported Features:** +- SCSI transparent command set +- FAT file system support (with FatFS integration) +- Multiple LUNs per device + +**Configuration:** +- ``CFG_TUH_MSC``: Number of MSC host instances +- ``CFG_TUH_MSC_MAXLUN``: Maximum LUNs per device + +**Key Functions:** +- ``tuh_msc_ready()``: Check if device is ready +- ``tuh_msc_read10()``: Read sectors from device +- ``tuh_msc_write10()``: Write sectors to device + +Hub +--- + +Support for USB hubs to connect multiple devices. + +**Features:** +- Multi-level hub support +- Port power management +- Device connect/disconnect detection + +**Configuration:** +- ``CFG_TUH_HUB``: Number of hub instances +- ``CFG_TUH_DEVICE_MAX``: Total connected devices + +Class Implementation Guidelines +=============================== + +Descriptor Requirements +----------------------- + +Each USB class requires specific descriptors: + +1. **Interface Descriptor**: Defines the class type +2. **Endpoint Descriptors**: Define communication endpoints +3. **Class-Specific Descriptors**: Additional class requirements +4. **String Descriptors**: Human-readable device information + +Callback Implementation +----------------------- + +Most classes require callback functions: + +- **Mandatory callbacks**: Must be implemented for class to function +- **Optional callbacks**: Provide additional functionality +- **Event callbacks**: Called when specific events occur + +Performance Considerations +-------------------------- + +- **Buffer Sizes**: Match endpoint buffer sizes to expected data rates +- **Transfer Types**: Use appropriate USB transfer types (bulk, interrupt, isochronous) +- **CPU Usage**: Minimize processing in interrupt context +- **Memory Usage**: Static allocation only, no dynamic memory + +Testing and Validation +---------------------- + +- **USB-IF Compliance**: Ensure descriptors meet USB standards +- **Host Compatibility**: Test with multiple operating systems +- **Performance Testing**: Verify transfer rates and latency +- **Error Handling**: Test disconnect/reconnect scenarios + +Class-Specific Resources +======================== + +- **USB-IF Specifications**: Official USB class specifications +- **Example Code**: Reference implementations in ``examples/`` directory +- **Test Applications**: Host-side test applications for validation +- **Debugging Tools**: USB protocol analyzers and debugging utilities \ No newline at end of file diff --git a/docs/troubleshooting.rst b/docs/troubleshooting.rst new file mode 100644 index 000000000..1f0f388df --- /dev/null +++ b/docs/troubleshooting.rst @@ -0,0 +1,318 @@ +*************** +Troubleshooting +*************** + +This guide helps you diagnose and fix common issues when developing with TinyUSB. + +Build Issues +============ + +Toolchain Problems +------------------ + +**"arm-none-eabi-gcc: command not found"** + +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 + + # macOS with Homebrew + brew install --cask gcc-arm-embedded + + # Windows: Download from ARM website and add to PATH + +**"make: command not found" or CMake errors** + +Build tools are missing. + +*Solution*: +.. code-block:: bash + + # Ubuntu/Debian + sudo apt-get install build-essential cmake + + # macOS + xcode-select --install + brew install cmake + +Dependency Issues +----------------- + +**"No rule to make target" or missing header files** + +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 + + # Or from example directory + cd examples/device/cdc_msc + make BOARD=your_board get-deps + +**Board Not Found** + +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 +============== + +Device Mode Problems +-------------------- + +**Device not recognized by host** + +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 +4. Check device manager (Windows) or ``dmesg`` (Linux) + +*Common causes and solutions*: + +- **Invalid descriptors**: Review ``usb_descriptors.c`` carefully +- **``tud_task()`` not called**: Ensure regular calls in main loop (< 1ms interval) +- **Wrong USB configuration**: Check ``tusb_config.h`` settings +- **Hardware issues**: Verify USB pins, crystal/clock configuration + +**Enumeration starts but fails** + +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 + +**Data transfer issues** + +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 + +Host Mode Problems +------------------ + +**No devices detected** + +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 + +**Device enumeration fails** + +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 + +**Class driver issues** + +Device enumerates but class-specific communication fails. + +*Troubleshooting*: +- Check device descriptors match expected class +- Verify interface/endpoint assignments +- Some devices need device-specific handling + +Performance Issues +================== + +Slow Transfer Speeds +-------------------- + +**Symptoms**: Lower than expected USB transfer rates + +*Causes and solutions*: +- **Task scheduling**: Call ``tud_task()``/``tuh_task()`` more frequently +- **Endpoint buffer sizes**: Increase buffer sizes for bulk transfers +- **DMA usage**: Enable DMA for USB transfers if supported +- **USB speed**: Use High Speed (480 Mbps) instead of Full Speed (12 Mbps) + +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 +- Use DMA for data transfers + +Memory Issues +============= + +Stack Overflow +-------------- + +**Symptoms**: Hard faults, random crashes, especially during enumeration + +*Diagnosis*: +- Build with ``DEBUG=1`` and use debugger +- Check stack pointer before/after USB operations +- Monitor stack usage with RTOS tools + +*Solutions*: +- Increase stack size in linker script +- Reduce local variable usage in callbacks +- Use static buffers instead of large stack arrays + +Heap Issues +----------- + +**Note**: TinyUSB doesn't use dynamic allocation, but your application might. + +*Check*: +- Application code using malloc/free +- RTOS heap usage +- Third-party library allocations + +Hardware-Specific Issues +======================== + +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 + +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 + +**Flash/RAM constraints**: +- Large USB applications may exceed RP2040 limits +- Use code optimization and remove unused features + +ESP32 Issues +------------ + +**USB peripheral differences**: +- ESP32-S2/S3 have different USB capabilities +- Some variants only support device mode +- DMA configuration varies between models + +Advanced Debugging +================== + +Using USB Analyzers +------------------- + +For complex issues, hardware USB analyzers provide detailed protocol traces: + +- **Wireshark** with USBPcap (Windows) or usbmon (Linux) +- **Hardware analyzers**: Total Phase Beagle, LeCroy USB analyzers +- **Logic analyzers**: For timing analysis of USB signals + +Debugging with GDB +------------------ + +.. code-block:: bash + + # Build with debug info + make BOARD=your_board DEBUG=1 all + + # Use with debugger + arm-none-eabi-gdb build/your_app.elf + +*Useful breakpoints*: +- ``dcd_int_handler()`` - USB interrupt entry +- ``tud_task()`` - Main device task +- Class-specific callbacks + +Custom Logging +-------------- + +For production debugging, implement custom logging: + +.. code-block:: c + + // In tusb_config.h + #define CFG_TUSB_DEBUG_PRINTF my_printf + + // Your implementation + void my_printf(const char* format, ...) { + // Send to RTT, SWO, or custom interface + } + +Getting Help +============ + +When reporting issues: + +1. **Minimal reproducible example**: Simplify to bare minimum +2. **Build information**: Board, toolchain version, build flags +3. **Logs**: Include output with ``LOG=2`` enabled +4. **Hardware details**: Board revision, USB connections, power supply +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 \ No newline at end of file diff --git a/docs/tutorials/first_device.rst b/docs/tutorials/first_device.rst new file mode 100644 index 000000000..9fac2df49 --- /dev/null +++ b/docs/tutorials/first_device.rst @@ -0,0 +1,147 @@ +********************* +Your First USB Device +********************* + +This tutorial walks you through creating a simple USB CDC (serial) device using TinyUSB. By the end, you'll have a working USB device that appears as a serial port on your computer. + +Prerequisites +============= + +* Completed :doc:`getting_started` tutorial +* Development board with USB device capability (e.g., STM32F4 Discovery, Raspberry Pi Pico) +* Basic understanding of C programming + +Understanding USB Device Basics +=============================== + +A USB device needs three key components: + +1. **USB Descriptors**: Tell the host what kind of device this is +2. **Class Implementation**: Handle USB class-specific requests (CDC, HID, etc.) +3. **Application Logic**: Your main application code + +Step 1: Choose Your Starting Point +================================== + +We'll start with the ``cdc_msc`` example as it's the most commonly used and well-tested. + +.. code-block:: bash + + cd examples/device/cdc_msc + +This example implements both CDC (virtual serial port) and MSC (mass storage) classes. + +Step 2: Understand the Code Structure +===================================== + +Key files in the example: + +* ``main.c`` - Main application loop and board initialization +* ``usb_descriptors.c`` - USB device descriptors +* ``tusb_config.h`` - TinyUSB stack configuration + +**Main Loop Pattern**: + +.. code-block:: c + + int main(void) { + board_init(); + tusb_init(); + + while (1) { + tud_task(); // TinyUSB device task + cdc_task(); // Application-specific CDC handling + } + } + +**Device Task**: ``tud_task()`` must be called regularly to handle USB events and maintain the connection. + +Step 3: Build and Test +====================== + +.. code-block:: bash + + # Fetch dependencies for your board family + python ../../../tools/get_deps.py stm32f4 # Replace with your family + + # Build for your board + make BOARD=stm32f407disco all + + # Flash to device + make BOARD=stm32f407disco flash + +**Expected Result**: After flashing, connect the USB port to your computer. You should see: + +* A new serial port device (e.g., ``/dev/ttyACM0`` on Linux, ``COMx`` on Windows) +* A small mass storage device + +Step 4: Customize for Your Needs +================================= + +**Simplify to CDC-only**: + +1. In ``tusb_config.h``, disable MSC: + +.. code-block:: c + + #define CFG_TUD_MSC 0 // Disable Mass Storage + +2. Remove MSC-related code from ``main.c`` and ``usb_descriptors.c`` + +**Modify Device Information**: + +In ``usb_descriptors.c``: + +.. code-block:: c + + tusb_desc_device_t const desc_device = { + .idVendor = 0xCafe, // Your vendor ID + .idProduct = 0x4000, // Your product ID + .bcdDevice = 0x0100, // Device version + // ... other fields + }; + +**Add Application Logic**: + +In the CDC task function, add your serial communication logic: + +.. code-block:: c + + void cdc_task(void) { + if (tud_cdc_available()) { + uint8_t buf[64]; + uint32_t count = tud_cdc_read(buf, sizeof(buf)); + + // Echo back what was received + tud_cdc_write(buf, count); + tud_cdc_write_flush(); + } + } + +Common Issues and Solutions +=========================== + +**Device Not Recognized**: + +* Check USB cable (must support data, not just power) +* Verify descriptors are valid using ``LOG=2`` build option +* Ensure ``tud_task()`` is called regularly in main loop + +**Build Errors**: + +* Missing dependencies: Run ``python tools/get_deps.py FAMILY`` +* Wrong board name: Check ``hw/bsp/FAMILY/boards/`` for valid names +* Compiler issues: Install ``gcc-arm-none-eabi`` + +**Runtime Issues**: + +* Hard faults: Check stack size in linker script +* USB not working: Verify clock configuration and USB pin setup +* Serial data corruption: Ensure proper flow control in CDC implementation + +Next Steps +========== + +* Learn about other device classes in :doc:`../reference/usb_classes` +* Understand advanced integration in :doc:`../guides/integration` +* Explore TinyUSB architecture in :doc:`../explanation/architecture` \ No newline at end of file diff --git a/docs/tutorials/first_host.rst b/docs/tutorials/first_host.rst new file mode 100644 index 000000000..5b406ad34 --- /dev/null +++ b/docs/tutorials/first_host.rst @@ -0,0 +1,160 @@ +****************** +Your First USB Host +****************** + +This tutorial guides you through creating a simple USB host application that can connect to and communicate with USB devices. + +Prerequisites +============= + +* Completed :doc:`getting_started` and :doc:`first_device` tutorials +* Development board with USB host capability (e.g., STM32F4 Discovery with USB-A connector) +* USB device to test with (USB drive, mouse, keyboard, or CDC device) + +Understanding USB Host Basics +============================= + +A USB host application needs: + +1. **Device Enumeration**: Detect and configure connected devices +2. **Class Drivers**: Handle communication with specific device types +3. **Application Logic**: Process data from/to the connected devices + +Step 1: Start with an Example +============================= + +Use the ``cdc_msc_hid`` host example: + +.. code-block:: bash + + cd examples/host/cdc_msc_hid + +This example can communicate with CDC (serial), MSC (storage), and HID (keyboard/mouse) devices. + +Step 2: Understand the Code Structure +===================================== + +Key components: + +* ``main.c`` - Main loop and device event handling +* Host callbacks - Functions called when devices connect/disconnect +* Class-specific handlers - Process data from different device types + +**Main Loop Pattern**: + +.. code-block:: c + + int main(void) { + board_init(); + tusb_init(); + + while (1) { + tuh_task(); // TinyUSB host task + // Handle connected devices + } + } + +**Connection Events**: TinyUSB calls your callbacks when devices connect: + +.. code-block:: c + + void tuh_mount_cb(uint8_t dev_addr) { + printf("Device connected, address = %d\\n", dev_addr); + } + + void tuh_umount_cb(uint8_t dev_addr) { + printf("Device disconnected, address = %d\\n", dev_addr); + } + +Step 3: Build and Test +====================== + +.. code-block:: bash + + # Fetch dependencies + python ../../../tools/get_deps.py stm32f4 + + # Build + make BOARD=stm32f407disco all + + # Flash + make BOARD=stm32f407disco flash + +**Testing**: Connect different USB devices and observe the output via serial console. + +Step 4: Handle Specific Device Types +==================================== + +**Mass Storage (USB Drive)**: + +.. code-block:: c + + void tuh_msc_mount_cb(uint8_t dev_addr) { + printf("USB Drive mounted\\n"); + // Read/write files + } + +**HID Devices (Keyboard/Mouse)**: + +.. code-block:: c + + void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, + uint8_t const* desc_report, uint16_t desc_len) { + uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance); + if (itf_protocol == HID_ITF_PROTOCOL_KEYBOARD) { + printf("Keyboard connected\\n"); + } + } + +**CDC Devices (Serial)**: + +.. code-block:: c + + void tuh_cdc_mount_cb(uint8_t idx) { + printf("CDC device mounted\\n"); + // Configure serial settings + tuh_cdc_set_baudrate(idx, 115200, NULL, 0); + } + +Common Issues and Solutions +=========================== + +**No Device Detection**: + +* Check power supply - host mode requires more power than device mode +* Verify USB connector wiring and type (USB-A for host vs USB micro/C for device) +* Enable logging with ``LOG=2`` to see enumeration process + +**Enumeration Failures**: + +* Some devices need more time - increase timeouts +* Check USB hub support if using a hub +* Verify device is USB 2.0 compatible (USB 3.0 devices should work in USB 2.0 mode) + +**Class Driver Issues**: + +* Not all devices follow standards perfectly - may need custom handling +* Check device descriptors with USB analyzer tools +* Some composite devices may not be fully supported + +Hardware Considerations +======================= + +**Power Requirements**: + +* Host mode typically requires external power or powered USB hub +* Check board documentation for power limitations +* Some boards need jumper changes to enable host power + +**Pin Configuration**: + +* Host and device modes often use different USB connectors/pins +* Verify board supports host mode on your chosen port +* Check if OTG (On-The-Go) configuration is needed + +Next Steps +========== + +* Learn about supported USB classes in :doc:`../reference/usb_classes` +* Understand advanced integration in :doc:`../guides/integration` +* Explore TinyUSB architecture in :doc:`../explanation/architecture` \ No newline at end of file diff --git a/docs/reference/getting_started.rst b/docs/tutorials/getting_started.rst similarity index 73% rename from docs/reference/getting_started.rst rename to docs/tutorials/getting_started.rst index b891d911b..7853a9cc0 100644 --- a/docs/reference/getting_started.rst +++ b/docs/tutorials/getting_started.rst @@ -2,20 +2,22 @@ Getting Started *************** +This tutorial will guide you through setting up TinyUSB for your first project. We'll cover the basic integration steps and build your first example. + Add TinyUSB to your project --------------------------- -To incorporate tinyusb to your project +To incorporate TinyUSB into your project: -* Copy or ``git submodule`` this repo into your project in a subfolder. Let's say it is ``your_project/tinyusb`` -* Add all the ``.c`` in the ``tinyusb/src`` folder to your project -* Add ``your_project/tinyusb/src`` to your include path. Also make sure your current include path also contains the configuration file ``tusb_config.h``. -* Make sure all required macros are all defined properly in ``tusb_config.h`` (configure file in demo application is sufficient, but you need to add a few more such as ``CFG_TUSB_MCU``, ``CFG_TUSB_OS`` since they are passed by make/cmake to maintain a unique configure for all boards). -* If you use the device stack, make sure you have created/modified usb descriptors for your own need. Ultimately you need to implement all **tud descriptor** callbacks for the stack to work. -* Add ``tusb_init(rhport, role)`` call to your reset initialization code. -* Call ``tusb_int_handler(rhport, in_isr)`` in your USB IRQ Handler -* Implement all enabled classes's callbacks. -* If you don't use any RTOSes at all, you need to continuously and/or periodically call ``tud_task()``/``tuh_task()`` function. All of the callbacks and functionality are handled and invoked within the call of that task runner. +* Copy or ``git submodule`` this repository into your project in a subfolder. Let's say it is ``your_project/tinyusb`` +* Add all the ``.c`` files in the ``tinyusb/src`` folder to your project +* Add ``your_project/tinyusb/src`` to your include path. Also make sure your current include path contains the configuration file ``tusb_config.h``. +* Make sure all required macros are defined properly in ``tusb_config.h`` (the configuration file in demo applications is sufficient, but you need to add a few more such as ``CFG_TUSB_MCU``, ``CFG_TUSB_OS`` since they are passed by make/cmake to maintain a unique configuration for all boards). +* If you use the device stack, make sure you have created/modified USB descriptors for your own needs. Ultimately you need to implement all **tud descriptor** callbacks for the stack to work. +* Add a ``tusb_init(rhport, role)`` call to your reset initialization code. +* Call ``tusb_int_handler(rhport, in_isr)`` in your USB IRQ handler +* Implement all enabled classes' callbacks. +* If you don't use any RTOS at all, you need to continuously and/or periodically call the ``tud_task()``/``tuh_task()`` functions. All of the callbacks and functionality are handled and invoked within the call of that task runner. .. code-block:: c @@ -57,20 +59,20 @@ For your convenience, TinyUSB contains a handful of examples for both host and d $ git clone https://github.com/hathach/tinyusb tinyusb $ cd tinyusb -Some ports will also require a port-specific SDK (e.g. RP2040) or binary (e.g. Sony Spresense) to build examples. They are out of scope for tinyusb, you should download/install it first according to its manufacturer guide. +Some ports will also require a port-specific SDK (e.g. RP2040) or binary (e.g. Sony Spresense) to build examples. They are out of scope for TinyUSB, you should download/install them first according to the manufacturer's guide. Dependencies ^^^^^^^^^^^^ -The hardware code is located in ``hw/bsp`` folder, and is organized by family/boards. e.g raspberry_pi_pico is located in ``hw/bsp/rp2040/boards/raspberry_pi_pico`` where ``FAMILY=rp2040`` and ``BOARD=raspberry_pi_pico``. Before building, we firstly need to download dependencies such as: MCU low-level peripheral driver and external libraries e.g FreeRTOS (required by some examples). We can do that by either ways: +The hardware code is located in the ``hw/bsp`` folder, and is organized by family/boards. For example, raspberry_pi_pico is located in ``hw/bsp/rp2040/boards/raspberry_pi_pico`` where ``FAMILY=rp2040`` and ``BOARD=raspberry_pi_pico``. Before building, we first need to download dependencies such as: MCU low-level peripheral drivers and external libraries like FreeRTOS (required by some examples). We can do this in either of two ways: -1. Run ``tools/get_deps.py {FAMILY}`` script to download all dependencies for a family as follow. Note: For TinyUSB developer to download all dependencies, use FAMILY=all. +1. Run the ``tools/get_deps.py {FAMILY}`` script to download all dependencies for a family as follows. Note: For TinyUSB developers to download all dependencies, use FAMILY=all. .. code-block:: bash $ python tools/get_deps.py rp2040 -2. Or run the ``get-deps`` target in one of the example folder as follow. +2. Or run the ``get-deps`` target in one of the example folders as follows. .. code-block:: bash @@ -82,7 +84,7 @@ You only need to do this once per family. Check out :doc:`complete list of depen Build Examples ^^^^^^^^^^^^^^ -Examples support make and cmake build system for most MCUs, however some MCU families such as espressif or rp2040 only support cmake. First change directory to an example folder. +Examples support make and cmake build systems for most MCUs, however some MCU families such as Espressif or RP2040 only support cmake. First change directory to an example folder. .. code-block:: bash @@ -267,3 +269,25 @@ Following these steps: 2. Create new project in IAR, in Tool chain dropdown menu, choose CMake for Arm then Import ``CMakeLists.txt`` from chosen example directory. 3. Set up board option in ``Option - CMake/CMSIS-TOOLBOX - CMake``, for example ``-DBOARD=stm32f439nucleo -DTOOLCHAIN=iar``, **Uncheck 'Override tools in env'**. 4. (For debug only) Choose correct CPU model in ``Option - General Options - Target``, to profit register and memory view. + +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 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 + +**Runtime Issues** + +* **Device not recognized**: Check USB descriptors implementation and ``tusb_config.h`` settings +* **Enumeration failure**: Enable logging with ``LOG=2`` and check for USB protocol errors +* **Hard faults/crashes**: Verify interrupt handler setup and stack size allocation + +Next Steps +---------- + +* Try the :doc:`first_device` tutorial to implement a simple USB device +* Read about :doc:`../guides/integration` for production projects +* Check :doc:`../reference/boards` for board-specific information diff --git a/docs/tutorials/index.rst b/docs/tutorials/index.rst new file mode 100644 index 000000000..6cf8f6ded --- /dev/null +++ b/docs/tutorials/index.rst @@ -0,0 +1,12 @@ +********* +Tutorials +********* + +Step-by-step learning guides for TinyUSB development. + +.. toctree:: + :maxdepth: 2 + + getting_started + first_device + first_host \ No newline at end of file From e7b851d9ac2657e591f772dd3fa326e2d8d00270 Mon Sep 17 00:00:00 2001 From: c1570 Date: Thu, 25 Sep 2025 00:20:45 +0200 Subject: [PATCH 02/13] Naming conventions, buffer handling --- docs/explanation/usb_concepts.rst | 94 +++++++++++++++++++++++++++++- docs/reference/configuration.rst | 5 ++ docs/reference/glossary.rst | 10 +++- docs/tutorials/getting_started.rst | 3 + 4 files changed, 107 insertions(+), 5 deletions(-) diff --git a/docs/explanation/usb_concepts.rst b/docs/explanation/usb_concepts.rst index 02ba76770..e276b4c96 100644 --- a/docs/explanation/usb_concepts.rst +++ b/docs/explanation/usb_concepts.rst @@ -4,6 +4,18 @@ USB Concepts This document provides a brief introduction to USB protocol fundamentals that are essential for understanding TinyUSB development. +TinyUSB API Naming Conventions +=============================== + +TinyUSB uses consistent function prefixes to organize its API: + +* **tusb_**: Core stack functions (initialization, interrupt handling) +* **tud_**: Device stack functions (e.g., ``tud_task()``, ``tud_cdc_write()``) +* **tuh_**: Host stack functions (e.g., ``tuh_task()``, ``tuh_cdc_receive()``) +* **tu_**: Internal utility functions (generally not used by applications) + +This naming makes it easy to identify which part of the stack a function belongs to and ensures there are no naming conflicts when using both device and host stacks together. + USB Protocol Basics ==================== @@ -252,10 +264,10 @@ USB supports multiple speed modes: **TinyUSB Speed Support**: Most TinyUSB ports support Full Speed and High Speed. Speed is typically auto-detected by hardware. Configure speed requirements in board configuration (``hw/bsp/FAMILY/boards/BOARD/board.mk``) and ensure your MCU supports the desired speed. -USB Device Controllers -====================== +USB Controller Abstraction +=========================== -USB device controllers are hardware peripherals that handle the low-level USB protocol implementation. Understanding how they work helps explain TinyUSB's architecture and portability. +USB controllers are hardware peripherals that handle the low-level USB protocol implementation. Understanding how they work helps explain TinyUSB's architecture and portability. Controller Fundamentals ----------------------- @@ -316,6 +328,42 @@ These internal details don't matter to users of TinyUSB typically; however, when - ``dcd_int_handler()`` - Process USB interrupts - ``dcd_connect()/dcd_disconnect()`` - Control USB bus connection +Host Controller Driver (HCD) +----------------------------- + +TinyUSB also abstracts USB host controllers through the **Host Controller Driver (HCD)** layer for host mode applications. + +**Portable Interface** (``src/host/usbh.h``): +- Standardized interface for all host controllers +- Common device enumeration and pipe management +- Unified transfer scheduling and completion handling + +**Common HCD Functions**: +- ``hcd_init()`` - Initialize host controller hardware +- ``hcd_port_connect_status()`` - Check device connection status +- ``hcd_port_reset()`` - Reset connected device +- ``hcd_edpt_open()`` - Open communication pipe to device endpoint +- ``hcd_edpt_xfer()`` - Transfer data to/from connected device + +**Host vs Device Architecture**: While DCD is reactive (responds to host requests), HCD is active (initiates all communication). Host controllers manage device enumeration, driver loading, and transfer scheduling to multiple connected devices. + +TinyUSB Event System & Thread Safety +==================================== + +Deferred Interrupt Processing +----------------------------- + +**Core Architectural Principle**: TinyUSB uses a deferred interrupt processing model where all USB hardware events are captured in interrupt service routines (ISRs) but processed later in non-interrupt context. + +**Event Flow**: + +1. **Hardware Event**: USB controller generates interrupt (e.g., data received, transfer complete) +2. **ISR Handling**: TinyUSB ISR captures the event and pushes it to a central event queue +3. **Deferred Processing**: Application calls ``tud_task()`` or ``tuh_task()`` to process queued events +4. **Class Driver Callbacks**: Events trigger appropriate class driver functions and user callbacks + +**Buffer Integration**: The deferred processing model works seamlessly with TinyUSB's buffer/FIFO design. Since callbacks run in task context (not ISR), it's safe and straightforward to enqueue TX data directly in RX callbacks - for example, processing incoming CDC data and immediately sending a response. + Controller Event Flow --------------------- @@ -329,6 +377,46 @@ Controller Event Flow 6. **Class Notification**: Appropriate class drivers handle the event 7. **Application Callback**: User code responds to the event +USB Class Driver Architecture +============================== + +TinyUSB implements USB classes through a standardized driver pattern that provides consistent integration with the core stack while allowing class-specific functionality. + +Class Driver Pattern +--------------------- + +**Standardized Entry Points**: Each class driver implements these core functions: + +- ``*_init()`` - Initialize class driver state and buffers +- ``*_reset()`` - Reset to initial state on USB bus reset +- ``*_open()`` - Parse and configure interfaces during enumeration +- ``*_control_xfer_cb()`` - Handle class-specific control requests +- ``*_xfer_cb()`` - Handle transfer completion callbacks + +**Multi-Instance Support**: Classes support multiple instances using ``_n`` suffixed APIs: + +.. code-block:: c + + // Single instance (default instance 0) + tud_cdc_write(data, len); + + // Multiple instances + tud_cdc_n_write(0, data, len); // Instance 0 + tud_cdc_n_write(1, data, len); // Instance 1 + +**Integration with Core Stack**: Class drivers are automatically discovered and integrated through function pointers in driver tables. The core stack calls class drivers during enumeration, control requests, and data transfers without requiring explicit registration. + +Class Driver Types +------------------- + +TinyUSB classes have different architectural patterns based on their buffering capabilities and callback designs. + +Most classes like CDC, MIDI, and HID always use internal buffers for data management. These classes provide notification-only callbacks such as ``tud_cdc_rx_cb(uint8_t itf)`` that signal when data is available, requiring applications to use class-specific APIs like ``tud_cdc_read()`` and ``tud_cdc_write()`` to access the data. HID is slightly different in that it provides direct buffer access in some callbacks (``tud_hid_set_report_cb()`` receives buffer and size parameters), but it still maintains internal endpoint buffering that cannot be disabled. + +The **Vendor Class** is unique in that it supports both buffered and direct modes. When buffered, vendor class behaves like other classes with ``tud_vendor_read()`` and ``tud_vendor_write()`` APIs. However, when buffering is disabled by setting buffer size to 0, the vendor class provides direct buffer access through ``tud_vendor_rx_cb(itf, buffer, bufsize)`` callbacks, eliminating internal FIFO overhead and providing direct endpoint control. + +**Block-Oriented Classes** like MSC operate differently by handling large data blocks through callback interfaces. The application implements storage access functions such as ``tud_msc_read10_cb()`` and ``tud_msc_write10_cb()``, while the TinyUSB stack manages the USB protocol aspects and the application manages the underlying storage. + Power Management ================ diff --git a/docs/reference/configuration.rst b/docs/reference/configuration.rst index 8d6dd6190..79aeb15d8 100644 --- a/docs/reference/configuration.rst +++ b/docs/reference/configuration.rst @@ -106,6 +106,11 @@ Device Classes #define CFG_TUD_VENDOR 1 // Number of vendor interfaces #define CFG_TUD_VENDOR_EPSIZE 64 // Vendor endpoint size + #define CFG_TUD_VENDOR_RX_BUFSIZE 64 // RX buffer size (0 = no buffering) + #define CFG_TUD_VENDOR_TX_BUFSIZE 64 // TX buffer size (0 = no buffering) + +.. note:: + Unlike other classes, vendor class supports setting buffer sizes to 0 to disable internal buffering. When disabled, data goes directly to ``tud_vendor_rx_cb()`` and the ``tud_vendor_read()``/``tud_vendor_write()`` functions are not available - applications must handle data directly in callbacks. Host Stack Configuration ======================== diff --git a/docs/reference/glossary.rst b/docs/reference/glossary.rst index e6e92738f..56ee49619 100644 --- a/docs/reference/glossary.rst +++ b/docs/reference/glossary.rst @@ -14,7 +14,7 @@ Glossary USB transfer type used for device configuration and control. All USB devices must support control transfers on endpoint 0. DCD - Device Controller Driver. The hardware abstraction layer for USB device controllers in TinyUSB. + Device Controller Driver. The hardware abstraction layer for USB device controllers in TinyUSB. See also HCD. Descriptor Data structures that describe USB device capabilities, configuration, and interfaces to the host. @@ -32,7 +32,7 @@ Glossary Process where USB host discovers and configures a newly connected device. HCD - Host Controller Driver. The hardware abstraction layer for USB host controllers in TinyUSB. + Host Controller Driver. The hardware abstraction layer for USB host controllers in TinyUSB. See also DCD. HID Human Interface Device. USB class for input devices like keyboards, mice, and game controllers. @@ -73,6 +73,12 @@ Glossary Super Speed USB 3.0 speed mode operating at 5 Gbps. Not supported by TinyUSB. + tud + TinyUSB Device. Function prefix for all device stack APIs (e.g., ``tud_task()``, ``tud_cdc_write()``). + + tuh + TinyUSB Host. Function prefix for all host stack APIs (e.g., ``tuh_task()``, ``tuh_cdc_receive()``). + UAC USB Audio Class. USB class for audio devices. diff --git a/docs/tutorials/getting_started.rst b/docs/tutorials/getting_started.rst index 7853a9cc0..432b0b682 100644 --- a/docs/tutorials/getting_started.rst +++ b/docs/tutorials/getting_started.rst @@ -19,6 +19,9 @@ To incorporate TinyUSB into your project: * Implement all enabled classes' callbacks. * If you don't use any RTOS at all, you need to continuously and/or periodically call the ``tud_task()``/``tuh_task()`` functions. All of the callbacks and functionality are handled and invoked within the call of that task runner. +.. 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. + .. code-block:: c int main(void) { From 75f2a8451e6ab622f8974b77b76b16ac2d057349 Mon Sep 17 00:00:00 2001 From: c1570 Date: Thu, 25 Sep 2025 01:01:01 +0200 Subject: [PATCH 03/13] improve flow --- docs/explanation/architecture.rst | 25 ++++++------------ docs/explanation/usb_concepts.rst | 23 +++-------------- docs/reference/configuration.rst | 14 +++++++--- docs/reference/usb_classes.rst | 5 +--- docs/troubleshooting.rst | 43 ++++--------------------------- docs/tutorials/first_device.rst | 8 ++++-- 6 files changed, 34 insertions(+), 84 deletions(-) diff --git a/docs/explanation/architecture.rst b/docs/explanation/architecture.rst index 4c63b198d..aa0c76128 100644 --- a/docs/explanation/architecture.rst +++ b/docs/explanation/architecture.rst @@ -12,10 +12,7 @@ Memory Safety TinyUSB is designed for resource-constrained embedded systems with strict memory requirements: -- **No dynamic allocation**: All memory is statically allocated at compile time -- **Bounded buffers**: All buffers have compile-time defined sizes -- **Stack-based design**: No heap usage in the core stack -- **Predictable memory usage**: Memory consumption is deterministic +TinyUSB uses **no dynamic allocation** - all memory is statically allocated at compile time for predictability. All buffers have bounded, compile-time defined sizes to prevent overflow issues. The TinyUSB core avoids heap allocation, resulting in **predictable memory usage** where consumption is fully deterministic. Thread Safety ------------- @@ -54,7 +51,7 @@ TinyUSB follows a layered architecture from hardware to application: ├─────────────────────────────────────────┤ │ Device/Host Stack Core │ ← USB protocol handling ├─────────────────────────────────────────┤ - │ Hardware Abstraction (DCD/HCD) │ ← MCU-specific drivers + │ Hardware Abstraction (DCD/HCD) │ ← MCU-specific drivers ├─────────────────────────────────────────┤ │ OS Abstraction (OSAL) │ ← RTOS integration ├─────────────────────────────────────────┤ @@ -79,6 +76,8 @@ Component Overview Device Stack Architecture ========================= +This section is concerned with the **Device Stack**, i.e., the component of TinyUSB used in USB devices (that talk to a USB host). + Core Components --------------- @@ -138,6 +137,8 @@ TinyUSB uses a deferred interrupt model for thread safety: Host Stack Architecture ======================= +This section is concerned with the **Host Stack**, i.e., the component of TinyUSB used in USB hosts, managing connected USB devices. + Core Components --------------- @@ -223,12 +224,7 @@ Memory Management Static Allocation Model ----------------------- -TinyUSB uses only static memory allocation: - -- **Endpoint Buffers**: Fixed-size buffers for each endpoint -- **Class Buffers**: Static buffers for class-specific data -- **Control Buffers**: Fixed buffer for control transfers -- **Queue Buffers**: Static event queues +TinyUSB uses only static memory allocation; it allocates fixed-size endpoint buffers for each configured endpoint, static buffers for class-specific data handling, a fixed buffer dedicated to control transfers, and static event queues for deferred interrupt processing. Buffer Management ----------------- @@ -254,12 +250,7 @@ Threading Model Task-Based Design ----------------- -TinyUSB uses a cooperative task model: - -- **Main Tasks**: ``tud_task()`` for device, ``tuh_task()`` for host -- **Regular Execution**: Tasks must be called regularly (< 1ms typical) -- **Event Processing**: All USB events processed in task context -- **Callback Execution**: Application callbacks run in task context +TinyUSB uses a cooperative task model; it provides main tasks - ``tud_task()`` for device and ``tuh_task()`` for host operation. These tasks must be called regularly (typically less than 1ms intervals) to ensure all USB events are processed in task context, where application callbacks also execute. RTOS Integration ---------------- diff --git a/docs/explanation/usb_concepts.rst b/docs/explanation/usb_concepts.rst index e276b4c96..8b315aea2 100644 --- a/docs/explanation/usb_concepts.rst +++ b/docs/explanation/usb_concepts.rst @@ -134,27 +134,16 @@ Endpoint Basics Endpoint Configuration ---------------------- -Each endpoint is configured with: -- **Transfer type**: Control, bulk, interrupt, or isochronous -- **Direction**: IN, OUT, or bidirectional (control only) -- **Maximum packet size**: Depends on USB speed and transfer type -- **Interval**: For interrupt and isochronous endpoints +Each endpoint is configured with a specific **transfer type** (control, bulk, interrupt, or isochronous), a **direction** (IN, OUT, or bidirectional for control only), a **maximum packet size** that depends on USB speed and transfer type, and an **interval** for interrupt and isochronous endpoints. **TinyUSB Configuration**: Endpoint characteristics are defined in descriptors (``usb_descriptors.c``) and automatically configured by the stack. Buffer sizes are set via ``CFG_TUD_*_EP_BUFSIZE`` macros. Error Handling and Flow Control ------------------------------- -**Transfer Results**: USB transfers can complete with different results: -- **ACK**: Successful transfer -- **NAK**: Device not ready (used for flow control) -- **STALL**: Error condition or unsupported request -- **Timeout**: Transfer failed to complete in time +**Transfer Results**: USB transfers can complete with different results. An **ACK** indicates a successful transfer, while a **NAK** signals that the device is not ready (commonly used for flow control). A **STALL** response indicates an error condition or unsupported request, and **Timeout** occurs when a transfer fails to complete within the expected time frame. -**Flow Control in USB**: Unlike network protocols, USB doesn't use congestion control. Instead: -- Devices use NAK responses when not ready to receive data -- Applications implement buffering and proper timing -- Some classes (like CDC) support hardware flow control (RTS/CTS) +**Flow Control in USB**: Unlike network protocols, USB doesn't use traditional congestion control. Instead, devices use NAK responses when not ready to receive data, applications implement buffering and proper timing strategies, and some classes (like CDC) support hardware flow control mechanisms such as RTS/CTS. **TinyUSB Handling**: Transfer results are represented as ``xfer_result_t`` enum values. The stack automatically handles NAK responses and timing. STALL conditions indicate application-level errors that should be addressed in class drivers. @@ -278,11 +267,7 @@ Controller Fundamentals - Generate interrupts for USB events - Implement USB electrical specifications -**Key Components**: -- **Physical Layer**: USB signal drivers and receivers -- **Protocol Engine**: Handles USB packets, ACK/NAK responses -- **Endpoint Buffers**: Hardware FIFOs or RAM for data storage -- **Interrupt Controller**: Generates events for software processing +**Key Components**: USB controllers consist of several key components working together. The **Physical Layer** provides USB signal drivers and receivers for electrical interfacing. The **Protocol Engine** handles USB packets and ACK/NAK responses according to the USB specification. **Endpoint Buffers** provide hardware FIFOs or RAM for data storage during transfers. Finally, the **Interrupt Controller** generates events for software processing when USB activities occur. Controller Architecture Types ----------------------------- diff --git a/docs/reference/configuration.rst b/docs/reference/configuration.rst index 79aeb15d8..fa0a874f5 100644 --- a/docs/reference/configuration.rst +++ b/docs/reference/configuration.rst @@ -173,15 +173,21 @@ Memory Management RTOS Configuration ------------------ -**FreeRTOS**: +TinyUSB supports multiple operating systems through its OSAL (Operating System Abstraction Layer). Choose the appropriate configuration based on your target environment. + +**FreeRTOS Integration**: + +When using FreeRTOS, configure the task queue sizes to handle USB events efficiently: .. code-block:: c #define CFG_TUSB_OS OPT_OS_FREERTOS - #define CFG_TUD_TASK_QUEUE_SZ 16 - #define CFG_TUH_TASK_QUEUE_SZ 16 + #define CFG_TUD_TASK_QUEUE_SZ 16 // Device task queue size + #define CFG_TUH_TASK_QUEUE_SZ 16 // Host task queue size -**RT-Thread**: +**RT-Thread Integration**: + +RT-Thread requires only the OS selection, as it uses the RTOS's built-in primitives: .. code-block:: c diff --git a/docs/reference/usb_classes.rst b/docs/reference/usb_classes.rst index 00a251ffb..387587b48 100644 --- a/docs/reference/usb_classes.rst +++ b/docs/reference/usb_classes.rst @@ -268,10 +268,7 @@ Most classes require callback functions: Performance Considerations -------------------------- -- **Buffer Sizes**: Match endpoint buffer sizes to expected data rates -- **Transfer Types**: Use appropriate USB transfer types (bulk, interrupt, isochronous) -- **CPU Usage**: Minimize processing in interrupt context -- **Memory Usage**: Static allocation only, no dynamic memory +When implementing USB classes, match **buffer sizes** to expected data rates to avoid bottlenecks. Choose appropriate **transfer types** based on your application's requirements. Keep **callback processing** lightweight for optimal performance. Avoid **memory allocations in critical paths** where possible to maintain consistent performance. Testing and Validation ---------------------- diff --git a/docs/troubleshooting.rst b/docs/troubleshooting.rst index 1f0f388df..e30210d01 100644 --- a/docs/troubleshooting.rst +++ b/docs/troubleshooting.rst @@ -177,11 +177,7 @@ Slow Transfer Speeds **Symptoms**: Lower than expected USB transfer rates -*Causes and solutions*: -- **Task scheduling**: Call ``tud_task()``/``tuh_task()`` more frequently -- **Endpoint buffer sizes**: Increase buffer sizes for bulk transfers -- **DMA usage**: Enable DMA for USB transfers if supported -- **USB speed**: Use High Speed (480 Mbps) instead of Full Speed (12 Mbps) +*Causes and solutions*: Improve **task scheduling** by calling ``tud_task()``/``tuh_task()`` more frequently to ensure timely USB event processing. Consider increasing **endpoint buffer sizes** for bulk transfers to reduce the frequency of small transfers. Enable **DMA usage** for USB transfers if your hardware supports it to offload CPU processing. Finally, use **High Speed** (480 Mbps) instead of Full Speed (12 Mbps) when possible to achieve better throughput. High CPU Usage -------------- @@ -194,34 +190,6 @@ High CPU Usage - Optimize descriptor parsing - Use DMA for data transfers -Memory Issues -============= - -Stack Overflow --------------- - -**Symptoms**: Hard faults, random crashes, especially during enumeration - -*Diagnosis*: -- Build with ``DEBUG=1`` and use debugger -- Check stack pointer before/after USB operations -- Monitor stack usage with RTOS tools - -*Solutions*: -- Increase stack size in linker script -- Reduce local variable usage in callbacks -- Use static buffers instead of large stack arrays - -Heap Issues ------------ - -**Note**: TinyUSB doesn't use dynamic allocation, but your application might. - -*Check*: -- Application code using malloc/free -- RTOS heap usage -- Third-party library allocations - Hardware-Specific Issues ======================== @@ -246,10 +214,6 @@ RP2040 Issues - CPU overclocking may be needed for reliable operation - Timing-sensitive - avoid long interrupt disable periods -**Flash/RAM constraints**: -- Large USB applications may exceed RP2040 limits -- Use code optimization and remove unused features - ESP32 Issues ------------ @@ -273,6 +237,9 @@ For complex issues, hardware USB analyzers provide detailed protocol traces: Debugging with GDB ------------------ +Debugging with traditional debuggers is limited due to the real time nature of USB. +However, especially for diagnosis of crashes, it can still be useful. + .. code-block:: bash # Build with debug info @@ -315,4 +282,4 @@ When reporting issues: **Resources**: - GitHub Discussions: https://github.com/hathach/tinyusb/discussions - Issue Tracker: https://github.com/hathach/tinyusb/issues -- Documentation: https://docs.tinyusb.org \ No newline at end of file +- Documentation: https://docs.tinyusb.org diff --git a/docs/tutorials/first_device.rst b/docs/tutorials/first_device.rst index 9fac2df49..1b9ed5b0a 100644 --- a/docs/tutorials/first_device.rst +++ b/docs/tutorials/first_device.rst @@ -40,7 +40,7 @@ Key files in the example: * ``usb_descriptors.c`` - USB device descriptors * ``tusb_config.h`` - TinyUSB stack configuration -**Main Loop Pattern**: +The main loop follows a simple pattern that combines board initialization, TinyUSB initialization, and continuous task processing: .. code-block:: c @@ -54,11 +54,13 @@ Key files in the example: } } -**Device Task**: ``tud_task()`` must be called regularly to handle USB events and maintain the connection. +The ``tud_task()`` function must be called regularly to handle USB events and maintain the connection with the host. This function processes all queued USB events and triggers appropriate callbacks in your application code. Step 3: Build and Test ====================== +With a clear understanding of the code structure, you're ready to build and test the example. This process involves fetching dependencies, compiling for your target board, and flashing the firmware: + .. code-block:: bash # Fetch dependencies for your board family @@ -78,6 +80,8 @@ Step 3: Build and Test Step 4: Customize for Your Needs ================================= +Once you have the basic example working, you can customize it for your specific application. The following modifications demonstrate common customization patterns. + **Simplify to CDC-only**: 1. In ``tusb_config.h``, disable MSC: From a332acf5ead28089c732428a4254354baec9afd6 Mon Sep 17 00:00:00 2001 From: c1570 Date: Thu, 25 Sep 2025 01:18:56 +0200 Subject: [PATCH 04/13] rearrage TOC --- docs/index.rst | 30 ++++++++++-------------------- 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/docs/index.rst b/docs/index.rst index 9fbc5bd30..3a70f2471 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -27,31 +27,16 @@ TinyUSB provides a complete USB stack implementation supporting both device and Documentation Structure ----------------------- -.. toctree:: - :maxdepth: 2 - :caption: Learning - - tutorials/index - -.. toctree:: - :maxdepth: 2 - :caption: Problem Solving - - guides/index - faq - troubleshooting - .. toctree:: :maxdepth: 2 :caption: Information - reference/index - -.. toctree:: - :maxdepth: 2 - :caption: Understanding - explanation/index + tutorials/index + guides/index + reference/index + faq + troubleshooting .. toctree:: :maxdepth: 1 @@ -67,3 +52,8 @@ Documentation Structure Source Code Issue Tracker Discussions + +GitHub Project Main README +========================== + +.. include:: ../README_processed.rst From 39e2e5167c3b59176293023eaf0249a5b3955f0c Mon Sep 17 00:00:00 2001 From: c1570 Date: Fri, 26 Sep 2025 18:34:10 +0200 Subject: [PATCH 05/13] improved getting_started, integrated "first device/host" --- docs/explanation/usb_concepts.rst | 6 +- docs/faq.rst | 2 +- docs/guides/index.rst | 10 - docs/guides/integration.rst | 494 ----------------------------- docs/reference/glossary.rst | 3 + docs/tutorials/first_device.rst | 151 --------- docs/tutorials/first_host.rst | 160 ---------- docs/tutorials/getting_started.rst | 206 +++++++----- docs/tutorials/index.rst | 4 +- 9 files changed, 141 insertions(+), 895 deletions(-) delete mode 100644 docs/guides/index.rst delete mode 100644 docs/guides/integration.rst delete mode 100644 docs/tutorials/first_device.rst delete mode 100644 docs/tutorials/first_host.rst diff --git a/docs/explanation/usb_concepts.rst b/docs/explanation/usb_concepts.rst index 8b315aea2..e3d400921 100644 --- a/docs/explanation/usb_concepts.rst +++ b/docs/explanation/usb_concepts.rst @@ -30,7 +30,7 @@ Host and Device Roles - Manages the USB bus - Enumerates and configures devices -**TinyUSB Host Stack**: Enable with ``CFG_TUH_ENABLED=1`` in ``tusb_config.h``. Call ``tuh_task()`` regularly in your main loop. See :doc:`../tutorials/first_host` for implementation details. +**TinyUSB Host Stack**: Enable with ``CFG_TUH_ENABLED=1`` in ``tusb_config.h``. Call ``tuh_task()`` regularly in your main loop. See the :doc:`../tutorials/getting_started` Quick Start Examples for implementation details. **USB Device**: The peripheral side (keyboard, mouse, storage device, etc.). Devices: - Respond to host requests @@ -38,7 +38,7 @@ Host and Device Roles - Receive power from the host - Must be enumerated by the host before use -**TinyUSB Device Stack**: Enable with ``CFG_TUD_ENABLED=1`` in ``tusb_config.h``. Call ``tud_task()`` regularly in your main loop. See :doc:`../tutorials/first_device` for implementation details. +**TinyUSB Device Stack**: Enable with ``CFG_TUD_ENABLED=1`` in ``tusb_config.h``. Call ``tud_task()`` regularly in your main loop. See the :doc:`../tutorials/getting_started` Quick Start Examples for implementation details. **OTG (On-The-Go)**: Some devices can switch between host and device roles dynamically. **TinyUSB Support**: Both stacks can be enabled simultaneously on OTG-capable hardware. See ``examples/dual/`` for dual-role implementations. @@ -422,4 +422,4 @@ Next Steps - Start with :doc:`../tutorials/getting_started` for basic setup - Review :doc:`../reference/configuration` for configuration options -- Check :doc:`../guides/integration` for advanced integration scenarios +- Explore :doc:`../examples` for advanced use cases diff --git a/docs/faq.rst b/docs/faq.rst index ede97032d..505833316 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -38,7 +38,7 @@ Run ``python tools/get_deps.py FAMILY`` where FAMILY is your MCU family (e.g., s **Q: Can I use my own build system instead of Make/CMake?** -Yes, just add all ``.c`` files from ``src/`` to your project and configure include paths. See :doc:`guides/integration` for details. +Yes, just add all ``.c`` files from ``src/`` to your project and configure include paths. See :doc:`tutorials/getting_started` for details. **Q: Error: "tusb_config.h: No such file or directory"** diff --git a/docs/guides/index.rst b/docs/guides/index.rst deleted file mode 100644 index cad3dd27f..000000000 --- a/docs/guides/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -********** -How-to Guides -********** - -Problem-solving guides for common TinyUSB development tasks. - -.. toctree:: - :maxdepth: 2 - - integration \ No newline at end of file diff --git a/docs/guides/integration.rst b/docs/guides/integration.rst deleted file mode 100644 index c135c5ec6..000000000 --- a/docs/guides/integration.rst +++ /dev/null @@ -1,494 +0,0 @@ -********************* -Integration Guide -********************* - -This guide covers integrating TinyUSB into production projects with your own build system, custom hardware, and specific requirements. - -Project Integration Methods -============================ - -Method 1: Git Submodule (Recommended) --------------------------------------- - -Best for projects using git version control. - -.. code-block:: bash - - # Add TinyUSB as submodule - git submodule add https://github.com/hathach/tinyusb.git lib/tinyusb - git submodule update --init --recursive - -**Advantages:** -- Pinned to specific TinyUSB version -- Easy to update with ``git submodule update`` -- Version control tracks exact TinyUSB commit - -Method 2: Package Manager Integration -------------------------------------- - -**PlatformIO:** - -.. code-block:: ini - - ; platformio.ini - [env:myboard] - platform = your_platform - board = your_board - framework = arduino ; or other framework - lib_deps = - https://github.com/hathach/tinyusb.git - -**CMake FetchContent:** - -.. code-block:: cmake - - include(FetchContent) - FetchContent_Declare( - tinyusb - GIT_REPOSITORY https://github.com/hathach/tinyusb.git - GIT_TAG master # or specific version tag - ) - FetchContent_MakeAvailable(tinyusb) - -Method 3: Direct Copy ---------------------- - -Copy TinyUSB source files directly into your project. - -.. code-block:: bash - - # Copy only source files - cp -r tinyusb/src/ your_project/lib/tinyusb/ - -**Note:** You'll need to manually update when TinyUSB releases new versions. - -Build System Integration -======================== - -Make/GCC Integration --------------------- - -**Makefile example:** - -.. code-block:: make - - # TinyUSB settings - TUSB_DIR = lib/tinyusb - TUSB_SRC_DIR = $(TUSB_DIR)/src - - # Include paths - CFLAGS += -I$(TUSB_SRC_DIR) - CFLAGS += -I. # For tusb_config.h - - # MCU and OS settings (pass to compiler) - CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_STM32F4 - CFLAGS += -DCFG_TUSB_OS=OPT_OS_NONE - - # TinyUSB source files - SRC_C += $(wildcard $(TUSB_SRC_DIR)/*.c) - SRC_C += $(wildcard $(TUSB_SRC_DIR)/common/*.c) - SRC_C += $(wildcard $(TUSB_SRC_DIR)/device/*.c) - SRC_C += $(wildcard $(TUSB_SRC_DIR)/class/*/*.c) - SRC_C += $(wildcard $(TUSB_SRC_DIR)/portable/$(VENDOR)/$(CHIP_FAMILY)/*.c) - -**Finding the right portable driver:** - -.. code-block:: bash - - # List available drivers - find lib/tinyusb/src/portable -name "*.c" | grep stm32 - # Use: lib/tinyusb/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c - -CMake Integration ------------------ - -**CMakeLists.txt example:** - -.. code-block:: cmake - - # TinyUSB configuration - set(FAMILY_MCUS STM32F4) # Set your MCU family - set(CFG_TUSB_MCU OPT_MCU_STM32F4) - set(CFG_TUSB_OS OPT_OS_FREERTOS) # or OPT_OS_NONE - - # Add TinyUSB - add_subdirectory(lib/tinyusb) - - # Your project - add_executable(your_app - src/main.c - src/usb_descriptors.c - # other sources - ) - - # Link TinyUSB - target_link_libraries(your_app - tinyusb_device # or tinyusb_host - # other libraries - ) - - # Include paths - target_include_directories(your_app PRIVATE - src/ # For tusb_config.h - ) - - # Compile definitions - target_compile_definitions(your_app PRIVATE - CFG_TUSB_MCU=${CFG_TUSB_MCU} - CFG_TUSB_OS=${CFG_TUSB_OS} - ) - -IAR Embedded Workbench ----------------------- - -Use project connection files for easy integration: - -1. Open IAR project -2. Add TinyUSB project connection: ``Tools → Configure Custom Argument Variables`` -3. Create ``TUSB`` group, add ``TUSB_DIR`` variable -4. Import ``tinyusb/tools/iar_template.ipcf`` - -Keil µVision ------------- - -.. code-block:: none - - # Add to project groups: - TinyUSB/Common: src/common/*.c - TinyUSB/Device: src/device/*.c, src/class/*/*.c - TinyUSB/Portable: src/portable/vendor/family/*.c - - # Include paths: - src/ # tusb_config.h location - lib/tinyusb/src/ - - # Preprocessor defines: - CFG_TUSB_MCU=OPT_MCU_STM32F4 - CFG_TUSB_OS=OPT_OS_NONE - -Configuration Setup -=================== - -Create tusb_config.h --------------------- - -This is the most critical file for TinyUSB integration: - -.. code-block:: c - - // tusb_config.h - #ifndef _TUSB_CONFIG_H_ - #define _TUSB_CONFIG_H_ - - // MCU selection - REQUIRED - #ifndef CFG_TUSB_MCU - #define CFG_TUSB_MCU OPT_MCU_STM32F4 - #endif - - // OS selection - REQUIRED - #ifndef CFG_TUSB_OS - #define CFG_TUSB_OS OPT_OS_NONE - #endif - - // Debug level - #define CFG_TUSB_DEBUG 0 - - // Device stack - #define CFG_TUD_ENABLED 1 - #define CFG_TUD_ENDPOINT0_SIZE 64 - - // Device classes - #define CFG_TUD_CDC 1 - #define CFG_TUD_HID 0 - #define CFG_TUD_MSC 0 - - // CDC configuration - #define CFG_TUD_CDC_EP_BUFSIZE 512 - #define CFG_TUD_CDC_RX_BUFSIZE 512 - #define CFG_TUD_CDC_TX_BUFSIZE 512 - - #endif - -USB Descriptors ---------------- - -Create or modify ``usb_descriptors.c`` for your device: - -.. code-block:: c - - #include "tusb.h" - - // Device descriptor - tusb_desc_device_t const desc_device = { - .bLength = sizeof(tusb_desc_device_t), - .bDescriptorType = TUSB_DESC_DEVICE, - .bcdUSB = 0x0200, - .bDeviceClass = TUSB_CLASS_MISC, - .bDeviceSubClass = MISC_SUBCLASS_COMMON, - .bDeviceProtocol = MISC_PROTOCOL_IAD, - .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE, - .idVendor = 0xCafe, // Your VID - .idProduct = 0x4000, // Your PID - .bcdDevice = 0x0100, - .iManufacturer = 0x01, - .iProduct = 0x02, - .iSerialNumber = 0x03, - .bNumConfigurations = 0x01 - }; - - // Get device descriptor - uint8_t const* tud_descriptor_device_cb(void) { - return (uint8_t const*)&desc_device; - } - - // Configuration descriptor - implement based on your needs - uint8_t const* tud_descriptor_configuration_cb(uint8_t index) { - // Return configuration descriptor - } - - // String descriptors - uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { - // Return string descriptors - } - -Application Integration -====================== - -Main Loop Integration --------------------- - -.. code-block:: c - - #include "tusb.h" - - int main(void) { - // Board/MCU initialization - board_init(); // Your board setup - - // USB stack initialization - tusb_init(); - - while (1) { - // USB device task - MUST be called regularly - tud_task(); - - // Your application code - your_app_task(); - } - } - -Interrupt Handler Setup ------------------------ - -**STM32 example:** - -.. code-block:: c - - // USB interrupt handler - void OTG_FS_IRQHandler(void) { - tud_int_handler(0); - } - -**RP2040 example:** - -.. code-block:: c - - void isr_usbctrl(void) { - tud_int_handler(0); - } - -Class Implementation --------------------- - -Implement required callbacks for enabled classes: - -.. code-block:: c - - // CDC class callbacks - void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding) { - // Handle line coding changes - } - - void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) { - // Handle DTR/RTS changes - } - -RTOS Integration -=============== - -FreeRTOS Integration -------------------- - -.. code-block:: c - - // USB task - void usb_device_task(void* param) { - while (1) { - tud_task(); - vTaskDelay(1); // 1ms delay - } - } - - // Create USB task - xTaskCreate(usb_device_task, "usbd", - 256, NULL, configMAX_PRIORITIES-1, NULL); - -**Configuration:** - -.. code-block:: c - - // In tusb_config.h - #define CFG_TUSB_OS OPT_OS_FREERTOS - #define CFG_TUD_TASK_QUEUE_SZ 16 - -RT-Thread Integration --------------------- - -.. code-block:: c - - // In tusb_config.h - #define CFG_TUSB_OS OPT_OS_RTTHREAD - - // USB thread - void usb_thread_entry(void* parameter) { - tusb_init(); - while (1) { - tud_task(); - rt_thread_mdelay(1); - } - } - -Custom Hardware Integration -=========================== - -Clock Configuration -------------------- - -USB requires precise 48MHz clock: - -**STM32 example:** - -.. code-block:: c - - // Configure PLL for 48MHz USB clock - RCC_OscInitStruct.PLL.PLLQ = 7; // Adjust for 48MHz - HAL_RCC_OscConfig(&RCC_OscInitStruct); - -**RP2040 example:** - -.. code-block:: c - - // USB clock is automatically configured by SDK - -Pin Configuration ------------------ - -Configure USB pins correctly: - -**STM32 example:** - -.. code-block:: c - - // USB pins: PA11 (DM), PA12 (DP) - GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; - GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; - GPIO_InitStruct.Pull = GPIO_NOPULL; - GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; - GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; - HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - -Power Management ---------------- - -For battery-powered applications: - -.. code-block:: c - - // Implement suspend/resume callbacks - void tud_suspend_cb(bool remote_wakeup_en) { - // Enter low power mode - } - - void tud_resume_cb(void) { - // Exit low power mode - } - -Testing and Validation -====================== - -Build Verification ------------------- - -.. code-block:: bash - - # Test build - make clean && make all - - # Check binary size - arm-none-eabi-size build/firmware.elf - - # Verify no undefined symbols - arm-none-eabi-nm build/firmware.elf | grep " U " - -Runtime Testing ---------------- - -1. **Device Recognition**: Check if device appears in system -2. **Enumeration**: Verify all descriptors are valid -3. **Class Functionality**: Test class-specific features -4. **Performance**: Measure transfer rates and latency -5. **Stress Testing**: Long-running tests with connect/disconnect - -Debugging Integration Issues -============================ - -Common Problems ---------------- - -1. **Device not recognized**: Check descriptors and configuration -2. **Build errors**: Verify include paths and source files -3. **Link errors**: Check library dependencies -4. **Runtime crashes**: Enable debug builds and use debugger -5. **Poor performance**: Profile code and optimize critical paths - -Debug Builds ------------- - -.. code-block:: c - - // In tusb_config.h for debugging - #define CFG_TUSB_DEBUG 2 - #define CFG_TUSB_DEBUG_PRINTF printf - -Enable logging to identify issues quickly. - -Production Considerations -========================= - -Code Size Optimization ----------------------- - -.. code-block:: c - - // Minimal configuration - #define CFG_TUSB_DEBUG 0 - #define CFG_TUD_CDC 1 - #define CFG_TUD_HID 0 - #define CFG_TUD_MSC 0 - // Disable unused classes - -Performance Optimization ------------------------- - -- Use DMA for USB transfers if available -- Optimize descriptor sizes -- Use appropriate endpoint buffer sizes -- Consider high-speed USB for high bandwidth applications - -Compliance and Certification ----------------------------- - -- Validate descriptors against USB specifications -- Test with USB-IF compliance tools -- Consider USB-IF certification for commercial products -- Test with multiple host operating systems \ No newline at end of file diff --git a/docs/reference/glossary.rst b/docs/reference/glossary.rst index 56ee49619..561780c53 100644 --- a/docs/reference/glossary.rst +++ b/docs/reference/glossary.rst @@ -4,6 +4,9 @@ Glossary .. glossary:: + BSP + Board Support Package. A collection of board-specific code that provides hardware abstraction for a particular development board, including pin mappings, clock settings, linker scripts, and hardware initialization routines. Located in ``hw/bsp/FAMILY/boards/BOARD_NAME``. + Bulk Transfer USB transfer type used for large amounts of data that doesn't require guaranteed timing. Used by mass storage devices and CDC class. diff --git a/docs/tutorials/first_device.rst b/docs/tutorials/first_device.rst deleted file mode 100644 index 1b9ed5b0a..000000000 --- a/docs/tutorials/first_device.rst +++ /dev/null @@ -1,151 +0,0 @@ -********************* -Your First USB Device -********************* - -This tutorial walks you through creating a simple USB CDC (serial) device using TinyUSB. By the end, you'll have a working USB device that appears as a serial port on your computer. - -Prerequisites -============= - -* Completed :doc:`getting_started` tutorial -* Development board with USB device capability (e.g., STM32F4 Discovery, Raspberry Pi Pico) -* Basic understanding of C programming - -Understanding USB Device Basics -=============================== - -A USB device needs three key components: - -1. **USB Descriptors**: Tell the host what kind of device this is -2. **Class Implementation**: Handle USB class-specific requests (CDC, HID, etc.) -3. **Application Logic**: Your main application code - -Step 1: Choose Your Starting Point -================================== - -We'll start with the ``cdc_msc`` example as it's the most commonly used and well-tested. - -.. code-block:: bash - - cd examples/device/cdc_msc - -This example implements both CDC (virtual serial port) and MSC (mass storage) classes. - -Step 2: Understand the Code Structure -===================================== - -Key files in the example: - -* ``main.c`` - Main application loop and board initialization -* ``usb_descriptors.c`` - USB device descriptors -* ``tusb_config.h`` - TinyUSB stack configuration - -The main loop follows a simple pattern that combines board initialization, TinyUSB initialization, and continuous task processing: - -.. code-block:: c - - int main(void) { - board_init(); - tusb_init(); - - while (1) { - tud_task(); // TinyUSB device task - cdc_task(); // Application-specific CDC handling - } - } - -The ``tud_task()`` function must be called regularly to handle USB events and maintain the connection with the host. This function processes all queued USB events and triggers appropriate callbacks in your application code. - -Step 3: Build and Test -====================== - -With a clear understanding of the code structure, you're ready to build and test the example. This process involves fetching dependencies, compiling for your target board, and flashing the firmware: - -.. code-block:: bash - - # Fetch dependencies for your board family - python ../../../tools/get_deps.py stm32f4 # Replace with your family - - # Build for your board - make BOARD=stm32f407disco all - - # Flash to device - make BOARD=stm32f407disco flash - -**Expected Result**: After flashing, connect the USB port to your computer. You should see: - -* A new serial port device (e.g., ``/dev/ttyACM0`` on Linux, ``COMx`` on Windows) -* A small mass storage device - -Step 4: Customize for Your Needs -================================= - -Once you have the basic example working, you can customize it for your specific application. The following modifications demonstrate common customization patterns. - -**Simplify to CDC-only**: - -1. In ``tusb_config.h``, disable MSC: - -.. code-block:: c - - #define CFG_TUD_MSC 0 // Disable Mass Storage - -2. Remove MSC-related code from ``main.c`` and ``usb_descriptors.c`` - -**Modify Device Information**: - -In ``usb_descriptors.c``: - -.. code-block:: c - - tusb_desc_device_t const desc_device = { - .idVendor = 0xCafe, // Your vendor ID - .idProduct = 0x4000, // Your product ID - .bcdDevice = 0x0100, // Device version - // ... other fields - }; - -**Add Application Logic**: - -In the CDC task function, add your serial communication logic: - -.. code-block:: c - - void cdc_task(void) { - if (tud_cdc_available()) { - uint8_t buf[64]; - uint32_t count = tud_cdc_read(buf, sizeof(buf)); - - // Echo back what was received - tud_cdc_write(buf, count); - tud_cdc_write_flush(); - } - } - -Common Issues and Solutions -=========================== - -**Device Not Recognized**: - -* Check USB cable (must support data, not just power) -* Verify descriptors are valid using ``LOG=2`` build option -* Ensure ``tud_task()`` is called regularly in main loop - -**Build Errors**: - -* Missing dependencies: Run ``python tools/get_deps.py FAMILY`` -* Wrong board name: Check ``hw/bsp/FAMILY/boards/`` for valid names -* Compiler issues: Install ``gcc-arm-none-eabi`` - -**Runtime Issues**: - -* Hard faults: Check stack size in linker script -* USB not working: Verify clock configuration and USB pin setup -* Serial data corruption: Ensure proper flow control in CDC implementation - -Next Steps -========== - -* Learn about other device classes in :doc:`../reference/usb_classes` -* Understand advanced integration in :doc:`../guides/integration` -* Explore TinyUSB architecture in :doc:`../explanation/architecture` \ No newline at end of file diff --git a/docs/tutorials/first_host.rst b/docs/tutorials/first_host.rst deleted file mode 100644 index 5b406ad34..000000000 --- a/docs/tutorials/first_host.rst +++ /dev/null @@ -1,160 +0,0 @@ -****************** -Your First USB Host -****************** - -This tutorial guides you through creating a simple USB host application that can connect to and communicate with USB devices. - -Prerequisites -============= - -* Completed :doc:`getting_started` and :doc:`first_device` tutorials -* Development board with USB host capability (e.g., STM32F4 Discovery with USB-A connector) -* USB device to test with (USB drive, mouse, keyboard, or CDC device) - -Understanding USB Host Basics -============================= - -A USB host application needs: - -1. **Device Enumeration**: Detect and configure connected devices -2. **Class Drivers**: Handle communication with specific device types -3. **Application Logic**: Process data from/to the connected devices - -Step 1: Start with an Example -============================= - -Use the ``cdc_msc_hid`` host example: - -.. code-block:: bash - - cd examples/host/cdc_msc_hid - -This example can communicate with CDC (serial), MSC (storage), and HID (keyboard/mouse) devices. - -Step 2: Understand the Code Structure -===================================== - -Key components: - -* ``main.c`` - Main loop and device event handling -* Host callbacks - Functions called when devices connect/disconnect -* Class-specific handlers - Process data from different device types - -**Main Loop Pattern**: - -.. code-block:: c - - int main(void) { - board_init(); - tusb_init(); - - while (1) { - tuh_task(); // TinyUSB host task - // Handle connected devices - } - } - -**Connection Events**: TinyUSB calls your callbacks when devices connect: - -.. code-block:: c - - void tuh_mount_cb(uint8_t dev_addr) { - printf("Device connected, address = %d\\n", dev_addr); - } - - void tuh_umount_cb(uint8_t dev_addr) { - printf("Device disconnected, address = %d\\n", dev_addr); - } - -Step 3: Build and Test -====================== - -.. code-block:: bash - - # Fetch dependencies - python ../../../tools/get_deps.py stm32f4 - - # Build - make BOARD=stm32f407disco all - - # Flash - make BOARD=stm32f407disco flash - -**Testing**: Connect different USB devices and observe the output via serial console. - -Step 4: Handle Specific Device Types -==================================== - -**Mass Storage (USB Drive)**: - -.. code-block:: c - - void tuh_msc_mount_cb(uint8_t dev_addr) { - printf("USB Drive mounted\\n"); - // Read/write files - } - -**HID Devices (Keyboard/Mouse)**: - -.. code-block:: c - - void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, - uint8_t const* desc_report, uint16_t desc_len) { - uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, instance); - if (itf_protocol == HID_ITF_PROTOCOL_KEYBOARD) { - printf("Keyboard connected\\n"); - } - } - -**CDC Devices (Serial)**: - -.. code-block:: c - - void tuh_cdc_mount_cb(uint8_t idx) { - printf("CDC device mounted\\n"); - // Configure serial settings - tuh_cdc_set_baudrate(idx, 115200, NULL, 0); - } - -Common Issues and Solutions -=========================== - -**No Device Detection**: - -* Check power supply - host mode requires more power than device mode -* Verify USB connector wiring and type (USB-A for host vs USB micro/C for device) -* Enable logging with ``LOG=2`` to see enumeration process - -**Enumeration Failures**: - -* Some devices need more time - increase timeouts -* Check USB hub support if using a hub -* Verify device is USB 2.0 compatible (USB 3.0 devices should work in USB 2.0 mode) - -**Class Driver Issues**: - -* Not all devices follow standards perfectly - may need custom handling -* Check device descriptors with USB analyzer tools -* Some composite devices may not be fully supported - -Hardware Considerations -======================= - -**Power Requirements**: - -* Host mode typically requires external power or powered USB hub -* Check board documentation for power limitations -* Some boards need jumper changes to enable host power - -**Pin Configuration**: - -* Host and device modes often use different USB connectors/pins -* Verify board supports host mode on your chosen port -* Check if OTG (On-The-Go) configuration is needed - -Next Steps -========== - -* Learn about supported USB classes in :doc:`../reference/usb_classes` -* Understand advanced integration in :doc:`../guides/integration` -* Explore TinyUSB architecture in :doc:`../explanation/architecture` \ No newline at end of file diff --git a/docs/tutorials/getting_started.rst b/docs/tutorials/getting_started.rst index 432b0b682..35a9aa9bf 100644 --- a/docs/tutorials/getting_started.rst +++ b/docs/tutorials/getting_started.rst @@ -2,22 +2,22 @@ Getting Started *************** -This tutorial will guide you through setting up TinyUSB for your first project. We'll cover the basic integration steps and build your first example. +This tutorial will guide you through setting up TinyUSB for your first project. We'll cover the basic integration steps and build your first example application. Add TinyUSB to your project --------------------------- To incorporate TinyUSB into your project: -* Copy or ``git submodule`` this repository into your project in a subfolder. Let's say it is ``your_project/tinyusb`` +* Copy this repository or add it as a git submodule to a subfolder in your project. For example, place it at ``your_project/tinyusb`` * Add all the ``.c`` files in the ``tinyusb/src`` folder to your project -* Add ``your_project/tinyusb/src`` to your include path. Also make sure your current include path contains the configuration file ``tusb_config.h``. -* Make sure all required macros are defined properly in ``tusb_config.h`` (the configuration file in demo applications is sufficient, but you need to add a few more such as ``CFG_TUSB_MCU``, ``CFG_TUSB_OS`` since they are passed by make/cmake to maintain a unique configuration for all boards). -* If you use the device stack, make sure you have created/modified USB descriptors for your own needs. Ultimately you need to implement all **tud descriptor** callbacks for the stack to work. +* Add ``your_project/tinyusb/src`` to your include path. Also ensure that your include path contains the configuration file ``tusb_config.h``. +* Ensure all required macros are properly defined in ``tusb_config.h``. The configuration file from the demo applications provides a good starting point, but you'll need to add additional macros such as ``CFG_TUSB_MCU`` and ``CFG_TUSB_OS``. These are typically passed by make/cmake to maintain unique configurations for different boards. +* If you're using the device stack, ensure you have created or modified USB descriptors to meet your specific requirements. Ultimately you need to implement all **tud descriptor** callbacks for the stack to work. * Add a ``tusb_init(rhport, role)`` call to your reset initialization code. -* Call ``tusb_int_handler(rhport, in_isr)`` in your USB IRQ handler +* Call ``tusb_int_handler(rhport, in_isr)`` from your USB IRQ handler * Implement all enabled classes' callbacks. -* If you don't use any RTOS at all, you need to continuously and/or periodically call the ``tud_task()``/``tuh_task()`` functions. All of the callbacks and functionality are handled and invoked within the call of that task runner. +* If you're not using an RTOS, you must call the ``tud_task()``/``tuh_task()`` functions continuously or periodically. These task functions handle all callbacks and core functionality. .. 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. @@ -62,14 +62,16 @@ For your convenience, TinyUSB contains a handful of examples for both host and d $ git clone https://github.com/hathach/tinyusb tinyusb $ cd tinyusb -Some ports will also require a port-specific SDK (e.g. RP2040) or binary (e.g. Sony Spresense) to build examples. They are out of scope for TinyUSB, you should download/install them first according to the manufacturer's guide. +Some ports require additional port-specific SDKs (e.g., for RP2040) or binaries (e.g., for Sony Spresense) to build examples. These components are outside the scope of TinyUSB, so you should download and install them first according to the manufacturer's documentation. Dependencies ^^^^^^^^^^^^ -The hardware code is located in the ``hw/bsp`` folder, and is organized by family/boards. For example, raspberry_pi_pico is located in ``hw/bsp/rp2040/boards/raspberry_pi_pico`` where ``FAMILY=rp2040`` and ``BOARD=raspberry_pi_pico``. Before building, we first need to download dependencies such as: MCU low-level peripheral drivers and external libraries like FreeRTOS (required by some examples). We can do this in either of two ways: +TinyUSB separates example applications from board-specific hardware configurations. Example applications live in ``examples/device``, ``examples/host``, and ``examples/dual`` directories, while Board Support Package (BSP) configurations are stored in ``hw/bsp/FAMILY/boards/BOARD_NAME``. The BSP provides hardware abstraction including pin mappings, clock settings, linker scripts, and hardware initialization routines. 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 an example with ``BOARD=raspberry_pi_pico``, the build system automatically finds and uses the corresponding BSP. -1. Run the ``tools/get_deps.py {FAMILY}`` script to download all dependencies for a family as follows. Note: For TinyUSB developers to download all dependencies, use FAMILY=all. +Before building, you must first download dependencies including MCU low-level peripheral drivers and external libraries such as FreeRTOS (required by some examples). You can do this in either of two ways: + +1. Run the ``tools/get_deps.py {FAMILY}`` script to download all dependencies for a specific MCU family. To download dependencies for all families, use ``FAMILY=all``. .. code-block:: bash @@ -87,7 +89,7 @@ You only need to do this once per family. Check out :doc:`complete list of depen Build Examples ^^^^^^^^^^^^^^ -Examples support make and cmake build systems for most MCUs, however some MCU families such as Espressif or RP2040 only support cmake. First change directory to an example folder. +Examples support both Make and CMake build systems for most MCUs. However, some MCU families (such as Espressif and RP2040) only support CMake. First change directory to an example folder. .. code-block:: bash @@ -111,7 +113,7 @@ To list all available targets with cmake $ cmake --build . --target help -Note: some examples especially those that uses Vendor class (e.g webUSB) may requires udev permission on Linux (and/or macOS) to access usb device. It depends on your OS distro, typically copy ``99-tinyusb.rules`` and reload your udev is good to go +Note: Some examples, especially those that use Vendor class (e.g., webUSB), may require udev permissions on Linux (and/or macOS) to access USB devices. It depends on your OS distribution, but typically copying ``99-tinyusb.rules`` and reloading udev is sufficient .. code-block:: bash @@ -132,7 +134,7 @@ If a board has several ports, one port is chosen by default in the individual bo Port Speed ~~~~~~~~~~ -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 F723 operate at full instead of default high speed +An MCU can support multiple operational speeds. By default, the example build system uses the fastest speed supported by the board. Use the option ``RHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED/OPT_MODE_HIGH_SPEED`` or ``RHPORT_HOST_SPEED=OPT_MODE_FULL_SPEED/OPT_MODE_HIGH_SPEED``. For example, to force the F723 to operate at full speed instead of the default high speed: .. code-block:: bash @@ -149,58 +151,10 @@ First install `linkermap tool `_ then ``li $ make BOARD=feather_nrf52840_express NO_LTO=1 all linkermap -Debug -^^^^^ +Flashing the Device +^^^^^^^^^^^^^^^^^^^ -To compile for debugging add ``DEBUG=1``\ , for example - -.. code-block:: bash - - $ make BOARD=feather_nrf52840_express DEBUG=1 all - - $ cmake -DBOARD=feather_nrf52840_express -DCMAKE_BUILD_TYPE=Debug .. - -Log -~~~ - -Should you have an issue running example and/or submitting an bug report. You could enable TinyUSB built-in debug logging with optional ``LOG=``. ``LOG=1`` will only print out error message, ``LOG=2`` print more information with on-going events. ``LOG=3`` or higher is not used yet. - -.. code-block:: bash - - $ make BOARD=feather_nrf52840_express LOG=2 all - - $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 .. - -Logger -~~~~~~ - -By default log message is printed via on-board UART which is slow and take lots of CPU time comparing to USB speed. If your board support on-board/external debugger, it would be more efficient to use it for logging. There are 2 protocols: - - -* `LOGGER=rtt`: use `Segger RTT protocol `_ - - * Cons: requires jlink as the debugger. - * Pros: work with most if not all MCUs - * Software viewer is JLink RTT Viewer/Client/Logger which is bundled with JLink driver package. - -* ``LOGGER=swo`` : Use dedicated SWO pin of ARM Cortex SWD debug header. - - * Cons: only work with ARM Cortex MCUs minus M0 - * Pros: should be compatible with more debugger that support SWO. - * Software viewer should be provided along with your debugger driver. - -.. code-block:: bash - - $ make BOARD=feather_nrf52840_express LOG=2 LOGGER=rtt all - $ make BOARD=feather_nrf52840_express LOG=2 LOGGER=swo all - - $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 -DLOGGER=rtt .. - $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 -DLOGGER=swo .. - -Flash -^^^^^ - -``flash`` target will use the default on-board debugger (jlink/cmsisdap/stlink/dfu) to flash the binary, please install those support software in advance. Some board use bootloader/DFU via serial which is required to pass to make command +The ``flash`` target uses the default on-board debugger (jlink/cmsisdap/stlink/dfu) to flash the binary. Please install the supporting software in advance. Some boards use bootloader/DFU via serial, which requires passing the serial port to the make command .. code-block:: bash @@ -217,7 +171,7 @@ Since jlink/openocd can be used with most of the boards, there is also ``flash-j $ cmake --build . --target cdc_msc-jlink $ cmake --build . --target cdc_msc-openocd -Some board use uf2 bootloader for drag & drop in to mass storage device, uf2 can be generated with ``uf2`` target +Some boards use UF2 bootloader for drag-and-drop into a mass storage device. UF2 files can be generated with the ``uf2`` target .. code-block:: bash @@ -225,21 +179,71 @@ Some board use uf2 bootloader for drag & drop in to mass storage device, uf2 can $ cmake --build . --target cdc_msc-uf2 +Debugging +^^^^^^^^^ + +To compile for debugging add ``DEBUG=1``\ , for example + +.. code-block:: bash + + $ make BOARD=feather_nrf52840_express DEBUG=1 all + + $ cmake -DBOARD=feather_nrf52840_express -DCMAKE_BUILD_TYPE=Debug .. + +Enable Logging +~~~~~~~~~~~~~~ + +If you encounter issues running examples or need to submit a bug report, you can enable TinyUSB's built-in debug logging with the optional ``LOG=`` parameter. ``LOG=1`` prints only error messages, while ``LOG=2`` prints more detailed information about ongoing events. ``LOG=3`` or higher is not used yet. + +.. code-block:: bash + + $ make BOARD=feather_nrf52840_express LOG=2 all + + $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 .. + +Logging Performance Impact +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +By default, log messages are printed via the on-board UART, which is slow and consumes significant CPU time compared to USB speeds. If your board supports an on-board or external debugger, it would be more efficient to use it for logging. There are 2 protocols: + + +* `LOGGER=rtt`: use `Segger RTT protocol `_ + + * Cons: requires jlink as the debugger. + * Pros: work with most if not all MCUs + * Software viewer is JLink RTT Viewer/Client/Logger which is bundled with JLink driver package. + +* ``LOGGER=swo``\ : Use dedicated SWO pin of ARM Cortex SWD debug header. + + * Cons: Only works with ARM Cortex MCUs except M0 + * Pros: should be compatible with more debugger that support SWO. + * Software viewer should be provided along with your debugger driver. + +.. code-block:: bash + + $ make BOARD=feather_nrf52840_express LOG=2 LOGGER=rtt all + $ make BOARD=feather_nrf52840_express LOG=2 LOGGER=swo all + + $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 -DLOGGER=rtt .. + $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 -DLOGGER=swo .. + IAR Support ^^^^^^^^^^^ +IAR Embedded Workbench is a commercial IDE and toolchain for embedded development. TinyUSB provides integration support for IAR through project connection files and native CMake support. + Use project connection ~~~~~~~~~~~~~~~~~~~~~~ IAR Project Connection files are provided to import TinyUSB stack into your project. -* A buildable project of your MCU need to be created in advance. +* A buildable project for your MCU needs to be created in advance. * Take example of STM32F0: - - You need ``stm32l0xx.h``, ``startup_stm32f0xx.s``, ``system_stm32f0xx.c``. + - You need ``stm32f0xx.h``, ``startup_stm32f0xx.s``, and ``system_stm32f0xx.c``. - - ``STM32L0xx_HAL_Driver`` is only needed to run examples, TinyUSB stack itself doesn't rely on MCU's SDKs. + - ``STM32F0xx_HAL_Driver`` is only needed to run examples, TinyUSB stack itself doesn't rely on MCU's SDKs. * Open ``Tools -> Configure Custom Argument Variables`` (Switch to ``Global`` tab if you want to do it for all your projects) Click ``New Group ...``, name it to ``TUSB``, Click ``Add Variable ...``, name it to ``TUSB_DIR``, change it's value to the path of your TinyUSB stack, @@ -279,7 +283,7 @@ 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 available boards in ``hw/bsp/FAMILY/boards/`` or run ``python tools/build.py -l`` +* **"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 **Runtime Issues** @@ -288,9 +292,65 @@ Common Issues and Solutions * **Enumeration failure**: Enable logging with ``LOG=2`` and check for USB protocol errors * **Hard faults/crashes**: Verify interrupt handler setup and stack size allocation -Next Steps ----------- +Quick Start Examples +-------------------- + +Now that you have TinyUSB set up, you can try these examples to see it in action. + +Simple Device Example +^^^^^^^^^^^^^^^^^^^^^ + +The ``cdc_msc`` example creates a USB device with both a virtual serial port (CDC) and mass storage (MSC). This is the most commonly used example and demonstrates core device functionality. + +**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:** + +.. code-block:: bash + + $ cd examples/device/cdc_msc + $ make BOARD=stm32f407disco all + $ make BOARD=stm32f407disco flash + +**Key files:** +* ``src/main.c`` - Main application with ``tud_task()`` loop +* ``src/usb_descriptors.c`` - USB device descriptors +* ``src/msc_disk.c`` - Mass storage implementation + +**Expected behavior:** Connect to your computer and you'll see both a new serial port and a small USB drive appear. + +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:** + +.. code-block:: bash + + $ cd examples/host/cdc_msc_hid + $ make BOARD=stm32f407disco all + $ make BOARD=stm32f407disco flash + +**Key files:** +* ``src/main.c`` - Main application with ``tuh_task()`` loop +* ``src/cdc_app.c`` - CDC host functionality +* ``src/msc_app.c`` - Mass storage host functionality +* ``src/hid_app.c`` - HID host functionality + +**Expected behavior:** Connect USB devices to see enumeration messages and device-specific interactions in the serial output. + +Next Steps +^^^^^^^^^^ -* Try the :doc:`first_device` tutorial to implement a simple USB device -* Read about :doc:`../guides/integration` for production projects * Check :doc:`../reference/boards` for board-specific information +* Explore more :doc:`../examples` for advanced use cases diff --git a/docs/tutorials/index.rst b/docs/tutorials/index.rst index 6cf8f6ded..dc362d717 100644 --- a/docs/tutorials/index.rst +++ b/docs/tutorials/index.rst @@ -7,6 +7,4 @@ Step-by-step learning guides for TinyUSB development. .. toctree:: :maxdepth: 2 - getting_started - first_device - first_host \ No newline at end of file + getting_started \ No newline at end of file From 82aa46d8ea9370944440cc40b87738ebeabb9593 Mon Sep 17 00:00:00 2001 From: c1570 Date: Sat, 27 Sep 2025 00:30:24 +0200 Subject: [PATCH 06/13] more consolidation --- docs/explanation/index.rst | 11 - docs/faq.rst | 2 +- docs/{tutorials => }/getting_started.rst | 11 +- docs/index.rst | 12 +- .../architecture.rst | 5 - docs/reference/configuration.rst | 307 ------------------ docs/reference/index.rst | 5 +- docs/reference/usb_classes.rst | 287 ---------------- .../usb_concepts.rst | 15 +- docs/tutorials/index.rst | 10 - 10 files changed, 22 insertions(+), 643 deletions(-) delete mode 100644 docs/explanation/index.rst rename docs/{tutorials => }/getting_started.rst (92%) rename docs/{explanation => reference}/architecture.rst (98%) delete mode 100644 docs/reference/configuration.rst delete mode 100644 docs/reference/usb_classes.rst rename docs/{explanation => reference}/usb_concepts.rst (95%) delete mode 100644 docs/tutorials/index.rst diff --git a/docs/explanation/index.rst b/docs/explanation/index.rst deleted file mode 100644 index 695efd9e0..000000000 --- a/docs/explanation/index.rst +++ /dev/null @@ -1,11 +0,0 @@ -*********** -Explanation -*********** - -Deep understanding of TinyUSB's design, architecture, and concepts. - -.. toctree:: - :maxdepth: 2 - - architecture - usb_concepts \ No newline at end of file diff --git a/docs/faq.rst b/docs/faq.rst index 505833316..ade51a379 100644 --- a/docs/faq.rst +++ b/docs/faq.rst @@ -38,7 +38,7 @@ Run ``python tools/get_deps.py FAMILY`` where FAMILY is your MCU family (e.g., s **Q: Can I use my own build system instead of Make/CMake?** -Yes, just add all ``.c`` files from ``src/`` to your project and configure include paths. See :doc:`tutorials/getting_started` for details. +Yes, just add all ``.c`` files from ``src/`` to your project and configure include paths. See :doc:`getting_started` for details. **Q: Error: "tusb_config.h: No such file or directory"** diff --git a/docs/tutorials/getting_started.rst b/docs/getting_started.rst similarity index 92% rename from docs/tutorials/getting_started.rst rename to docs/getting_started.rst index 35a9aa9bf..5e8ebd040 100644 --- a/docs/tutorials/getting_started.rst +++ b/docs/getting_started.rst @@ -13,11 +13,11 @@ To incorporate TinyUSB into your project: * Add all the ``.c`` files in the ``tinyusb/src`` folder to your project * Add ``your_project/tinyusb/src`` to your include path. Also ensure that your include path contains the configuration file ``tusb_config.h``. * Ensure all required macros are properly defined in ``tusb_config.h``. The configuration file from the demo applications provides a good starting point, but you'll need to add additional macros such as ``CFG_TUSB_MCU`` and ``CFG_TUSB_OS``. These are typically passed by make/cmake to maintain unique configurations for different boards. -* If you're using the device stack, ensure you have created or modified USB descriptors to meet your specific requirements. Ultimately you need to implement all **tud descriptor** callbacks for the stack to work. +* If you're using the **device stack**, you need to implement all **tud descriptor** callbacks for the stack to work. * Add a ``tusb_init(rhport, role)`` call to your reset initialization code. * Call ``tusb_int_handler(rhport, in_isr)`` from your USB IRQ handler * Implement all enabled classes' callbacks. -* If you're not using an RTOS, you must call the ``tud_task()``/``tuh_task()`` functions continuously or periodically. These task functions handle all callbacks and core functionality. +* If you're not using an RTOS, you must call the ``tud_task()``/``tuh_task()`` functions periodically. These task functions handle all callbacks and core functionality. .. 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. @@ -29,6 +29,7 @@ To incorporate TinyUSB into your project: .role = TUSB_ROLE_DEVICE, .speed = TUSB_SPEED_AUTO }; + // tud descriptor omitted here tusb_init(0, &dev_init); // initialize device stack on roothub port 0 tusb_rhport_init_t host_init = { @@ -67,7 +68,7 @@ Some ports require additional port-specific SDKs (e.g., for RP2040) or binaries Dependencies ^^^^^^^^^^^^ -TinyUSB separates example applications from board-specific hardware configurations. Example applications live in ``examples/device``, ``examples/host``, and ``examples/dual`` directories, while Board Support Package (BSP) configurations are stored in ``hw/bsp/FAMILY/boards/BOARD_NAME``. The BSP provides hardware abstraction including pin mappings, clock settings, linker scripts, and hardware initialization routines. 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 an example with ``BOARD=raspberry_pi_pico``, the build system automatically finds and uses the corresponding BSP. +TinyUSB separates example applications from board-specific hardware configurations (Board Support Packages, BSP). Example applications live in ``examples/device``, ``examples/host``, and ``examples/dual`` directories, while BSP configurations are stored in ``hw/bsp/FAMILY/boards/BOARD_NAME``. The BSP provides hardware abstraction including pin mappings, clock settings, linker scripts, and hardware initialization routines. 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 an example with ``BOARD=raspberry_pi_pico``, the build system automatically finds and uses the corresponding BSP. Before building, you must first download dependencies including MCU low-level peripheral drivers and external libraries such as FreeRTOS (required by some examples). You can do this in either of two ways: @@ -352,5 +353,5 @@ The ``cdc_msc_hid`` example creates a USB host that can connect to USB devices w Next Steps ^^^^^^^^^^ -* Check :doc:`../reference/boards` for board-specific information -* Explore more :doc:`../examples` for advanced use cases +* Check :doc:`reference/boards` for board-specific information +* Explore more examples in ``examples/device/`` and ``examples/host/`` directories diff --git a/docs/index.rst b/docs/index.rst index 3a70f2471..ac10dbfd7 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -18,10 +18,8 @@ TinyUSB provides a complete USB stack implementation supporting both device and **Quick Navigation:** -* New to TinyUSB? Start with :doc:`tutorials/getting_started` -* Need to solve a specific problem? Check :doc:`guides/index` -* Looking for API details? See :doc:`reference/index` -* Want to understand the design? Read :doc:`explanation/architecture` +* 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 @@ -31,12 +29,10 @@ Documentation Structure :maxdepth: 2 :caption: Information - explanation/index - tutorials/index - guides/index - reference/index + getting_started faq troubleshooting + reference/index .. toctree:: :maxdepth: 1 diff --git a/docs/explanation/architecture.rst b/docs/reference/architecture.rst similarity index 98% rename from docs/explanation/architecture.rst rename to docs/reference/architecture.rst index aa0c76128..ab451a91a 100644 --- a/docs/explanation/architecture.rst +++ b/docs/reference/architecture.rst @@ -239,11 +239,6 @@ Buffer Management - Size defined by ``CFG_TUD_*_RX/TX_BUFSIZE`` macros - Separate read/write pointers -**DMA Considerations**: -- Buffers must be DMA-accessible on some MCUs -- Alignment requirements vary by hardware -- Cache coherency handled in portable drivers - Threading Model =============== diff --git a/docs/reference/configuration.rst b/docs/reference/configuration.rst deleted file mode 100644 index fa0a874f5..000000000 --- a/docs/reference/configuration.rst +++ /dev/null @@ -1,307 +0,0 @@ -************* -Configuration -************* - -TinyUSB behavior is controlled through compile-time configuration in ``tusb_config.h``. This reference covers all available configuration options. - -Basic Configuration -=================== - -Required Settings ------------------ - -.. code-block:: c - - // Target MCU family - REQUIRED - #define CFG_TUSB_MCU OPT_MCU_STM32F4 - - // OS abstraction layer - REQUIRED - #define CFG_TUSB_OS OPT_OS_NONE - - // Enable device or host stack - #define CFG_TUD_ENABLED 1 // Device stack - #define CFG_TUH_ENABLED 1 // Host stack - -Debug and Logging ------------------ - -.. code-block:: c - - // Debug level (0=off, 1=error, 2=warning, 3=info) - #define CFG_TUSB_DEBUG 2 - - // Memory alignment for buffers (usually 4) - #define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4))) - -Device Stack Configuration -========================== - -Endpoint Configuration ----------------------- - -.. code-block:: c - - // Control endpoint buffer size - #define CFG_TUD_ENDPOINT0_SIZE 64 - - // Number of endpoints (excluding EP0) - #define CFG_TUD_ENDPOINT_MAX 16 - -Device Classes --------------- - -**CDC (Communication Device Class)**: - -.. code-block:: c - - #define CFG_TUD_CDC 1 // Number of CDC interfaces - #define CFG_TUD_CDC_EP_BUFSIZE 512 // CDC endpoint buffer size - #define CFG_TUD_CDC_RX_BUFSIZE 256 // CDC RX FIFO size - #define CFG_TUD_CDC_TX_BUFSIZE 256 // CDC TX FIFO size - -**HID (Human Interface Device)**: - -.. code-block:: c - - #define CFG_TUD_HID 1 // Number of HID interfaces - #define CFG_TUD_HID_EP_BUFSIZE 16 // HID endpoint buffer size - -**MSC (Mass Storage Class)**: - -.. code-block:: c - - #define CFG_TUD_MSC 1 // Number of MSC interfaces - #define CFG_TUD_MSC_EP_BUFSIZE 512 // MSC endpoint buffer size - -**Audio Class**: - -.. code-block:: c - - #define CFG_TUD_AUDIO 1 // Number of audio interfaces - #define CFG_TUD_AUDIO_FUNC_1_DESC_LEN 220 - #define CFG_TUD_AUDIO_FUNC_1_N_AS_INT 1 - #define CFG_TUD_AUDIO_FUNC_1_CTRL_BUF_SZ 64 - #define CFG_TUD_AUDIO_ENABLE_EP_IN 1 - #define CFG_TUD_AUDIO_FUNC_1_N_BYTES_PER_SAMPLE_TX 2 - #define CFG_TUD_AUDIO_FUNC_1_N_CHANNELS_TX 2 - -**MIDI**: - -.. code-block:: c - - #define CFG_TUD_MIDI 1 // Number of MIDI interfaces - #define CFG_TUD_MIDI_RX_BUFSIZE 128 // MIDI RX buffer size - #define CFG_TUD_MIDI_TX_BUFSIZE 128 // MIDI TX buffer size - -**DFU (Device Firmware Update)**: - -.. code-block:: c - - #define CFG_TUD_DFU 1 // Enable DFU mode - #define CFG_TUD_DFU_XFER_BUFSIZE 512 // DFU transfer buffer size - -**Vendor Class**: - -.. code-block:: c - - #define CFG_TUD_VENDOR 1 // Number of vendor interfaces - #define CFG_TUD_VENDOR_EPSIZE 64 // Vendor endpoint size - #define CFG_TUD_VENDOR_RX_BUFSIZE 64 // RX buffer size (0 = no buffering) - #define CFG_TUD_VENDOR_TX_BUFSIZE 64 // TX buffer size (0 = no buffering) - -.. note:: - Unlike other classes, vendor class supports setting buffer sizes to 0 to disable internal buffering. When disabled, data goes directly to ``tud_vendor_rx_cb()`` and the ``tud_vendor_read()``/``tud_vendor_write()`` functions are not available - applications must handle data directly in callbacks. - -Host Stack Configuration -======================== - -Port and Hub Configuration --------------------------- - -.. code-block:: c - - // Number of host root hub ports - #define CFG_TUH_HUB 1 - - // Number of connected devices (including hub) - #define CFG_TUH_DEVICE_MAX 5 - - // Control transfer buffer size - #define CFG_TUH_ENUMERATION_BUFSIZE 512 - -Host Classes ------------- - -**CDC Host**: - -.. code-block:: c - - #define CFG_TUH_CDC 2 // Number of CDC host instances - #define CFG_TUH_CDC_FTDI 1 // FTDI serial support - #define CFG_TUH_CDC_CP210X 1 // CP210x serial support - #define CFG_TUH_CDC_CH34X 1 // CH34x serial support - -**HID Host**: - -.. code-block:: c - - #define CFG_TUH_HID 4 // Number of HID instances - #define CFG_TUH_HID_EPIN_BUFSIZE 64 // HID endpoint buffer size - #define CFG_TUH_HID_EPOUT_BUFSIZE 64 - -**MSC Host**: - -.. code-block:: c - - #define CFG_TUH_MSC 1 // Number of MSC instances - #define CFG_TUH_MSC_MAXLUN 4 // Max LUNs per device - -Advanced Configuration -====================== - -Memory Management ------------------ - -.. code-block:: c - - // Enable stack protection - #define CFG_TUSB_DEBUG_PRINTF printf - - // Custom memory allocation (if needed) - #define CFG_TUSB_MEM_SECTION __attribute__((section(".usb_ram"))) - -RTOS Configuration ------------------- - -TinyUSB supports multiple operating systems through its OSAL (Operating System Abstraction Layer). Choose the appropriate configuration based on your target environment. - -**FreeRTOS Integration**: - -When using FreeRTOS, configure the task queue sizes to handle USB events efficiently: - -.. code-block:: c - - #define CFG_TUSB_OS OPT_OS_FREERTOS - #define CFG_TUD_TASK_QUEUE_SZ 16 // Device task queue size - #define CFG_TUH_TASK_QUEUE_SZ 16 // Host task queue size - -**RT-Thread Integration**: - -RT-Thread requires only the OS selection, as it uses the RTOS's built-in primitives: - -.. code-block:: c - - #define CFG_TUSB_OS OPT_OS_RTTHREAD - -Low Power Configuration ------------------------ - -.. code-block:: c - - // Enable remote wakeup - #define CFG_TUD_USBD_ENABLE_REMOTE_WAKEUP 1 - - // Suspend/resume callbacks - // Implement tud_suspend_cb() and tud_resume_cb() - -MCU-Specific Options -==================== - -The ``CFG_TUSB_MCU`` option selects the target microcontroller family: - -.. code-block:: c - - // STM32 families - #define CFG_TUSB_MCU OPT_MCU_STM32F0 - #define CFG_TUSB_MCU OPT_MCU_STM32F1 - #define CFG_TUSB_MCU OPT_MCU_STM32F4 - #define CFG_TUSB_MCU OPT_MCU_STM32F7 - #define CFG_TUSB_MCU OPT_MCU_STM32H7 - - // NXP families - #define CFG_TUSB_MCU OPT_MCU_LPC18XX - #define CFG_TUSB_MCU OPT_MCU_LPC40XX - #define CFG_TUSB_MCU OPT_MCU_LPC43XX - #define CFG_TUSB_MCU OPT_MCU_KINETIS_KL - #define CFG_TUSB_MCU OPT_MCU_IMXRT - - // Other vendors - #define CFG_TUSB_MCU OPT_MCU_RP2040 - #define CFG_TUSB_MCU OPT_MCU_ESP32S2 - #define CFG_TUSB_MCU OPT_MCU_ESP32S3 - #define CFG_TUSB_MCU OPT_MCU_SAMD21 - #define CFG_TUSB_MCU OPT_MCU_SAMD51 - #define CFG_TUSB_MCU OPT_MCU_NRF5X - -Configuration Examples -====================== - -Minimal Device (CDC only) --------------------------- - -.. code-block:: c - - #define CFG_TUSB_MCU OPT_MCU_STM32F4 - #define CFG_TUSB_OS OPT_OS_NONE - #define CFG_TUSB_DEBUG 0 - - #define CFG_TUD_ENABLED 1 - #define CFG_TUD_ENDPOINT0_SIZE 64 - - #define CFG_TUD_CDC 1 - #define CFG_TUD_CDC_EP_BUFSIZE 512 - #define CFG_TUD_CDC_RX_BUFSIZE 512 - #define CFG_TUD_CDC_TX_BUFSIZE 512 - - // Disable other classes - #define CFG_TUD_HID 0 - #define CFG_TUD_MSC 0 - #define CFG_TUD_MIDI 0 - #define CFG_TUD_AUDIO 0 - #define CFG_TUD_VENDOR 0 - -Full-Featured Host ------------------- - -.. code-block:: c - - #define CFG_TUSB_MCU OPT_MCU_STM32F4 - #define CFG_TUSB_OS OPT_OS_FREERTOS - #define CFG_TUSB_DEBUG 2 - - #define CFG_TUH_ENABLED 1 - #define CFG_TUH_HUB 1 - #define CFG_TUH_DEVICE_MAX 8 - #define CFG_TUH_ENUMERATION_BUFSIZE 512 - - #define CFG_TUH_CDC 2 - #define CFG_TUH_HID 4 - #define CFG_TUH_MSC 2 - #define CFG_TUH_VENDOR 2 - -Validation -========== - -Use these checks to validate your configuration: - -.. code-block:: c - - // In your main.c, add compile-time checks - #if !defined(CFG_TUSB_MCU) || (CFG_TUSB_MCU == OPT_MCU_NONE) - #error "CFG_TUSB_MCU must be defined" - #endif - - #if CFG_TUD_ENABLED && !defined(CFG_TUD_ENDPOINT0_SIZE) - #error "CFG_TUD_ENDPOINT0_SIZE must be defined for device stack" - #endif - -Common Configuration Issues -=========================== - -1. **Endpoint buffer size too small**: Causes transfer failures -2. **Missing CFG_TUSB_MCU**: Build will fail -3. **Incorrect OS setting**: RTOS functions won't work properly -4. **Insufficient endpoint count**: Device enumeration will fail -5. **Buffer size mismatches**: Data corruption or transfer failures - -For configuration examples specific to your board, check ``examples/device/*/tusb_config.h``. \ No newline at end of file diff --git a/docs/reference/index.rst b/docs/reference/index.rst index cb35dd1b9..d3c96eeee 100644 --- a/docs/reference/index.rst +++ b/docs/reference/index.rst @@ -7,9 +7,8 @@ Complete reference documentation for TinyUSB APIs, configuration, and supported .. toctree:: :maxdepth: 2 - api/index - configuration - usb_classes + architecture + usb_concepts boards dependencies concurrency diff --git a/docs/reference/usb_classes.rst b/docs/reference/usb_classes.rst deleted file mode 100644 index 387587b48..000000000 --- a/docs/reference/usb_classes.rst +++ /dev/null @@ -1,287 +0,0 @@ -*********** -USB Classes -*********** - -TinyUSB supports multiple USB device and host classes. This reference describes the features, capabilities, and requirements for each class. - -Device Classes -============== - -CDC (Communication Device Class) --------------------------------- - -Implements USB CDC specification for serial communication. - -**Supported Features:** -- CDC-ACM (Abstract Control Model) for virtual serial ports -- Data terminal ready (DTR) and request to send (RTS) control lines -- Line coding configuration (baud rate, parity, stop bits) -- Break signal support - -**Configuration:** -- ``CFG_TUD_CDC``: Number of CDC interfaces (1-4) -- ``CFG_TUD_CDC_EP_BUFSIZE``: Endpoint buffer size (typically 512) -- ``CFG_TUD_CDC_RX_BUFSIZE``: Receive FIFO size -- ``CFG_TUD_CDC_TX_BUFSIZE``: Transmit FIFO size - -**Key Functions:** -- ``tud_cdc_available()``: Check bytes available to read -- ``tud_cdc_read()``: Read data from host -- ``tud_cdc_write()``: Write data to host -- ``tud_cdc_write_flush()``: Flush transmit buffer - -**Callbacks:** -- ``tud_cdc_line_coding_cb()``: Line coding changed -- ``tud_cdc_line_state_cb()``: DTR/RTS state changed - -HID (Human Interface Device) ----------------------------- - -Implements USB HID specification for input devices. - -**Supported Features:** -- Boot protocol (keyboard/mouse) -- Report protocol with custom descriptors -- Input, output, and feature reports -- Multiple HID interfaces - -**Configuration:** -- ``CFG_TUD_HID``: Number of HID interfaces -- ``CFG_TUD_HID_EP_BUFSIZE``: Endpoint buffer size - -**Key Functions:** -- ``tud_hid_ready()``: Check if ready to send report -- ``tud_hid_report()``: Send HID report -- ``tud_hid_keyboard_report()``: Send keyboard report -- ``tud_hid_mouse_report()``: Send mouse report - -**Callbacks:** -- ``tud_hid_descriptor_report_cb()``: Provide report descriptor -- ``tud_hid_get_report_cb()``: Handle get report request -- ``tud_hid_set_report_cb()``: Handle set report request - -MSC (Mass Storage Class) ------------------------- - -Implements USB mass storage for file systems. - -**Supported Features:** -- SCSI transparent command set -- Multiple logical units (LUNs) -- Read/write operations -- Inquiry and capacity commands - -**Configuration:** -- ``CFG_TUD_MSC``: Number of MSC interfaces -- ``CFG_TUD_MSC_EP_BUFSIZE``: Endpoint buffer size - -**Key Functions:** -- Storage operations handled via callbacks - -**Required Callbacks:** -- ``tud_msc_inquiry_cb()``: Device inquiry information -- ``tud_msc_test_unit_ready_cb()``: Test if LUN is ready -- ``tud_msc_capacity_cb()``: Get LUN capacity -- ``tud_msc_start_stop_cb()``: Start/stop LUN -- ``tud_msc_read10_cb()``: Read data from LUN -- ``tud_msc_write10_cb()``: Write data to LUN - -Audio Class ------------ - -Implements USB Audio Class 2.0 specification. - -**Supported Features:** -- Audio streaming (input/output) -- Multiple sampling rates -- Volume and mute controls -- Feedback endpoints for asynchronous mode - -**Configuration:** -- ``CFG_TUD_AUDIO``: Number of audio functions -- Multiple configuration options for channels, sample rates, bit depth - -**Key Functions:** -- ``tud_audio_read()``: Read audio data -- ``tud_audio_write()``: Write audio data -- ``tud_audio_clear_ep_out_ff()``: Clear output FIFO - -MIDI ----- - -Implements USB MIDI specification. - -**Supported Features:** -- MIDI 1.0 message format -- Multiple virtual MIDI cables -- Standard MIDI messages - -**Configuration:** -- ``CFG_TUD_MIDI``: Number of MIDI interfaces -- ``CFG_TUD_MIDI_RX_BUFSIZE``: Receive buffer size -- ``CFG_TUD_MIDI_TX_BUFSIZE``: Transmit buffer size - -**Key Functions:** -- ``tud_midi_available()``: Check available MIDI messages -- ``tud_midi_read()``: Read MIDI packet -- ``tud_midi_write()``: Send MIDI packet - -DFU (Device Firmware Update) ----------------------------- - -Implements USB DFU specification for firmware updates. - -**Supported Modes:** -- DFU Mode: Device enters DFU for firmware update -- DFU Runtime: Request transition to DFU mode - -**Configuration:** -- ``CFG_TUD_DFU``: Enable DFU mode -- ``CFG_TUD_DFU_RUNTIME``: Enable DFU runtime - -**Key Functions:** -- Firmware update operations handled via callbacks - -**Required Callbacks:** -- ``tud_dfu_download_cb()``: Receive firmware data -- ``tud_dfu_manifest_cb()``: Complete firmware update - -Vendor Class ------------- - -Custom vendor-specific USB class implementation. - -**Features:** -- Configurable endpoints -- Custom protocol implementation -- WebUSB support -- Microsoft OS descriptors - -**Configuration:** -- ``CFG_TUD_VENDOR``: Number of vendor interfaces -- ``CFG_TUD_VENDOR_EPSIZE``: Endpoint size - -**Key Functions:** -- ``tud_vendor_available()``: Check available data -- ``tud_vendor_read()``: Read vendor data -- ``tud_vendor_write()``: Write vendor data - -Host Classes -============ - -CDC Host --------- - -Connect to CDC devices (virtual serial ports). - -**Supported Devices:** -- CDC-ACM devices -- FTDI USB-to-serial converters -- CP210x USB-to-serial converters -- CH34x USB-to-serial converters - -**Configuration:** -- ``CFG_TUH_CDC``: Number of CDC host instances -- ``CFG_TUH_CDC_FTDI``: Enable FTDI support -- ``CFG_TUH_CDC_CP210X``: Enable CP210x support - -**Key Functions:** -- ``tuh_cdc_available()``: Check available data -- ``tuh_cdc_read()``: Read from CDC device -- ``tuh_cdc_write()``: Write to CDC device -- ``tuh_cdc_set_baudrate()``: Configure serial settings - -HID Host --------- - -Connect to HID devices (keyboards, mice, etc.). - -**Supported Devices:** -- Boot keyboards and mice -- Generic HID devices with report descriptors -- Composite HID devices - -**Configuration:** -- ``CFG_TUH_HID``: Number of HID host instances -- ``CFG_TUH_HID_EPIN_BUFSIZE``: Input endpoint buffer size - -**Key Functions:** -- ``tuh_hid_receive_report()``: Start receiving reports -- ``tuh_hid_send_report()``: Send report to device -- ``tuh_hid_parse_report_descriptor()``: Parse HID descriptors - -MSC Host --------- - -Connect to mass storage devices (USB drives). - -**Supported Features:** -- SCSI transparent command set -- FAT file system support (with FatFS integration) -- Multiple LUNs per device - -**Configuration:** -- ``CFG_TUH_MSC``: Number of MSC host instances -- ``CFG_TUH_MSC_MAXLUN``: Maximum LUNs per device - -**Key Functions:** -- ``tuh_msc_ready()``: Check if device is ready -- ``tuh_msc_read10()``: Read sectors from device -- ``tuh_msc_write10()``: Write sectors to device - -Hub ---- - -Support for USB hubs to connect multiple devices. - -**Features:** -- Multi-level hub support -- Port power management -- Device connect/disconnect detection - -**Configuration:** -- ``CFG_TUH_HUB``: Number of hub instances -- ``CFG_TUH_DEVICE_MAX``: Total connected devices - -Class Implementation Guidelines -=============================== - -Descriptor Requirements ------------------------ - -Each USB class requires specific descriptors: - -1. **Interface Descriptor**: Defines the class type -2. **Endpoint Descriptors**: Define communication endpoints -3. **Class-Specific Descriptors**: Additional class requirements -4. **String Descriptors**: Human-readable device information - -Callback Implementation ------------------------ - -Most classes require callback functions: - -- **Mandatory callbacks**: Must be implemented for class to function -- **Optional callbacks**: Provide additional functionality -- **Event callbacks**: Called when specific events occur - -Performance Considerations --------------------------- - -When implementing USB classes, match **buffer sizes** to expected data rates to avoid bottlenecks. Choose appropriate **transfer types** based on your application's requirements. Keep **callback processing** lightweight for optimal performance. Avoid **memory allocations in critical paths** where possible to maintain consistent performance. - -Testing and Validation ----------------------- - -- **USB-IF Compliance**: Ensure descriptors meet USB standards -- **Host Compatibility**: Test with multiple operating systems -- **Performance Testing**: Verify transfer rates and latency -- **Error Handling**: Test disconnect/reconnect scenarios - -Class-Specific Resources -======================== - -- **USB-IF Specifications**: Official USB class specifications -- **Example Code**: Reference implementations in ``examples/`` directory -- **Test Applications**: Host-side test applications for validation -- **Debugging Tools**: USB protocol analyzers and debugging utilities \ No newline at end of file diff --git a/docs/explanation/usb_concepts.rst b/docs/reference/usb_concepts.rst similarity index 95% rename from docs/explanation/usb_concepts.rst rename to docs/reference/usb_concepts.rst index e3d400921..86ae97007 100644 --- a/docs/explanation/usb_concepts.rst +++ b/docs/reference/usb_concepts.rst @@ -30,7 +30,7 @@ Host and Device Roles - Manages the USB bus - Enumerates and configures devices -**TinyUSB Host Stack**: Enable with ``CFG_TUH_ENABLED=1`` in ``tusb_config.h``. Call ``tuh_task()`` regularly in your main loop. See the :doc:`../tutorials/getting_started` Quick Start Examples for implementation details. +**TinyUSB Host Stack**: Enable with ``CFG_TUH_ENABLED=1`` in ``tusb_config.h``. Call ``tuh_task()`` regularly in your main loop. See the :doc:`../getting_started` Quick Start Examples for implementation details. **USB Device**: The peripheral side (keyboard, mouse, storage device, etc.). Devices: - Respond to host requests @@ -38,7 +38,7 @@ Host and Device Roles - Receive power from the host - Must be enumerated by the host before use -**TinyUSB Device Stack**: Enable with ``CFG_TUD_ENABLED=1`` in ``tusb_config.h``. Call ``tud_task()`` regularly in your main loop. See the :doc:`../tutorials/getting_started` Quick Start Examples for implementation details. +**TinyUSB Device Stack**: Enable with ``CFG_TUD_ENABLED=1`` in ``tusb_config.h``. Call ``tud_task()`` regularly in your main loop. See the :doc:`../getting_started` Quick Start Examples for implementation details. **OTG (On-The-Go)**: Some devices can switch between host and device roles dynamically. **TinyUSB Support**: Both stacks can be enabled simultaneously on OTG-capable hardware. See ``examples/dual/`` for dual-role implementations. @@ -226,7 +226,10 @@ USB classes define standardized protocols for device types: - **DFU**: Device Firmware Update - Enable with ``CFG_TUD_DFU`` - **Vendor**: Custom vendor classes - Enable with ``CFG_TUD_VENDOR`` -See :doc:`../reference/usb_classes` for detailed class information and :doc:`../reference/configuration` for configuration options. +.. note:: + **Vendor Class Buffer Configuration**: Unlike other USB classes, the vendor class supports setting buffer sizes to 0 in ``tusb_config.h`` (``CFG_TUD_VENDOR_RX_BUFSIZE = 0``) to disable internal buffering. When disabled, data goes directly to ``tud_vendor_rx_cb()`` and the ``tud_vendor_read()``/``tud_vendor_write()`` functions are not available - applications must handle data directly in callbacks. + +See ``examples/device/*/tusb_config.h`` for configuration examples. USB Speeds ========== @@ -420,6 +423,6 @@ USB provides power to devices: Next Steps ========== -- Start with :doc:`../tutorials/getting_started` for basic setup -- Review :doc:`../reference/configuration` for configuration options -- Explore :doc:`../examples` for advanced use cases +- Start with :doc:`../getting_started` for basic setup +- Review ``examples/device/*/tusb_config.h`` for configuration examples +- Explore examples in ``examples/device/`` and ``examples/host/`` directories diff --git a/docs/tutorials/index.rst b/docs/tutorials/index.rst deleted file mode 100644 index dc362d717..000000000 --- a/docs/tutorials/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -********* -Tutorials -********* - -Step-by-step learning guides for TinyUSB development. - -.. toctree:: - :maxdepth: 2 - - getting_started \ No newline at end of file From 1f908d88ce4ba76d15d5b961a293327961deb7f9 Mon Sep 17 00:00:00 2001 From: c1570 Date: Sat, 27 Sep 2025 00:39:29 +0200 Subject: [PATCH 07/13] getting_started structure --- docs/getting_started.rst | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/getting_started.rst b/docs/getting_started.rst index 5e8ebd040..85f1f8a04 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -63,13 +63,14 @@ For your convenience, TinyUSB contains a handful of examples for both host and d $ git clone https://github.com/hathach/tinyusb tinyusb $ cd tinyusb -Some ports require additional port-specific SDKs (e.g., for RP2040) or binaries (e.g., for Sony Spresense) to build examples. These components are outside the scope of TinyUSB, so you should download and install them first according to the manufacturer's documentation. +TinyUSB separates example applications from board-specific hardware configurations (Board Support Packages, BSP). The BSP provides hardware abstraction including pin mappings, clock settings, linker scripts, and hardware initialization routines. + +* Example applications live in ``examples/device``, ``examples/host``, and ``examples/dual`` directories. +* BSP configurations are stored in ``hw/bsp/FAMILY/boards/BOARD_NAME``. 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 an example with ``BOARD=raspberry_pi_pico``, the build system automatically finds and uses the corresponding BSP. Dependencies ^^^^^^^^^^^^ -TinyUSB separates example applications from board-specific hardware configurations (Board Support Packages, BSP). Example applications live in ``examples/device``, ``examples/host``, and ``examples/dual`` directories, while BSP configurations are stored in ``hw/bsp/FAMILY/boards/BOARD_NAME``. The BSP provides hardware abstraction including pin mappings, clock settings, linker scripts, and hardware initialization routines. 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 an example with ``BOARD=raspberry_pi_pico``, the build system automatically finds and uses the corresponding BSP. - Before building, you must first download dependencies including MCU low-level peripheral drivers and external libraries such as FreeRTOS (required by some examples). You can do this in either of two ways: 1. Run the ``tools/get_deps.py {FAMILY}`` script to download all dependencies for a specific MCU family. To download dependencies for all families, use ``FAMILY=all``. From fa599e3ff4c41c471cd6db92fd924f95485942cd Mon Sep 17 00:00:00 2001 From: c1570 Date: Sun, 28 Sep 2025 00:40:29 +0200 Subject: [PATCH 08/13] streamlined getting_started --- docs/getting_started.rst | 425 ++++++++++++--------------------------- 1 file changed, 125 insertions(+), 300 deletions(-) diff --git a/docs/getting_started.rst b/docs/getting_started.rst index 85f1f8a04..84663e486 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -2,285 +2,157 @@ Getting Started *************** -This tutorial will guide you through setting up TinyUSB for your first project. We'll cover the basic integration steps and build your first example application. +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. -Add TinyUSB to your project ---------------------------- +Quick Start Examples +==================== -To incorporate TinyUSB into your project: +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. -* Copy this repository or add it as a git submodule to a subfolder in your project. For example, place it at ``your_project/tinyusb`` -* Add all the ``.c`` files in the ``tinyusb/src`` folder to your project -* Add ``your_project/tinyusb/src`` to your include path. Also ensure that your include path contains the configuration file ``tusb_config.h``. -* Ensure all required macros are properly defined in ``tusb_config.h``. The configuration file from the demo applications provides a good starting point, but you'll need to add additional macros such as ``CFG_TUSB_MCU`` and ``CFG_TUSB_OS``. These are typically passed by make/cmake to maintain unique configurations for different boards. -* If you're using the **device stack**, you need to implement all **tud descriptor** callbacks for the stack to work. -* Add a ``tusb_init(rhport, role)`` call to your reset initialization code. -* Call ``tusb_int_handler(rhport, in_isr)`` from your USB IRQ handler -* Implement all enabled classes' callbacks. -* If you're not using an RTOS, you must call the ``tud_task()``/``tuh_task()`` functions periodically. These task functions handle all callbacks and core functionality. +Simple Device Example +--------------------- -.. 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. +The `cdc_msc `_ example creates a USB device with both a virtual serial port (CDC) and mass storage (MSC). -.. code-block:: c +**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 - int main(void) { - tusb_rhport_init_t dev_init = { - .role = TUSB_ROLE_DEVICE, - .speed = TUSB_SPEED_AUTO - }; - // tud descriptor omitted here - tusb_init(0, &dev_init); // initialize device stack on roothub port 0 - - tusb_rhport_init_t host_init = { - .role = TUSB_ROLE_HOST, - .speed = TUSB_SPEED_AUTO - }; - tusb_init(1, &host_init); // initialize host stack on roothub port 1 - - while(1) { // the mainloop - your_application_code(); - tud_task(); // device task - tuh_task(); // host task - } - } - - void USB0_IRQHandler(void) { - tusb_int_handler(0, true); - } - - void USB1_IRQHandler(void) { - tusb_int_handler(1, true); - } - -Examples --------- - -For your convenience, TinyUSB contains a handful of examples for both host and device with/without RTOS to quickly test the functionality as well as demonstrate how API should be used. Most examples will work on most of :doc:`the supported boards `. Firstly we need to ``git clone`` if not already +**Build and run:** .. code-block:: bash $ git clone https://github.com/hathach/tinyusb tinyusb $ cd tinyusb - -TinyUSB separates example applications from board-specific hardware configurations (Board Support Packages, BSP). The BSP provides hardware abstraction including pin mappings, clock settings, linker scripts, and hardware initialization routines. - -* Example applications live in ``examples/device``, ``examples/host``, and ``examples/dual`` directories. -* BSP configurations are stored in ``hw/bsp/FAMILY/boards/BOARD_NAME``. 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 an example with ``BOARD=raspberry_pi_pico``, the build system automatically finds and uses the corresponding BSP. - -Dependencies -^^^^^^^^^^^^ - -Before building, you must first download dependencies including MCU low-level peripheral drivers and external libraries such as FreeRTOS (required by some examples). You can do this in either of two ways: - -1. Run the ``tools/get_deps.py {FAMILY}`` script to download all dependencies for a specific MCU family. To download dependencies for all families, use ``FAMILY=all``. - -.. code-block:: bash - - $ python tools/get_deps.py rp2040 - -2. Or run the ``get-deps`` target in one of the example folders as follows. - -.. code-block:: bash - + $ python tools/get_deps.py stm32f4 # Download dependencies $ cd examples/device/cdc_msc - $ make BOARD=feather_nrf52840_express get-deps + $ make BOARD=stm32f407disco all flash -You only need to do this once per family. Check out :doc:`complete list of dependencies and their designated path here ` +Connect to your computer and you'll see both a new serial port and a small USB drive appear. -Build Examples -^^^^^^^^^^^^^^ +Simple Host Example +------------------- -Examples support both Make and CMake build systems for most MCUs. However, some MCU families (such as Espressif and RP2040) only support CMake. First change directory to an example folder. +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:** .. code-block:: bash - $ cd examples/device/cdc_msc + $ python tools/get_deps.py stm32f4 # If not done already + $ cd examples/host/cdc_msc_hid + $ make BOARD=stm32f407disco all flash -Then compile with make or cmake +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 +============================ + +Once you've seen TinyUSB working, here's how to integrate it into your own project: + +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 all ``.c`` files from ``tinyusb/src/`` to your project + +3. **Configure include paths**: Add ``your_project/tinyusb/src`` to your include path. Ensure your include path contains ``tusb_config.h`` + +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 + +5. **Implement USB descriptors**: For device stack, implement all ``tud_descriptor_*_cb()`` callbacks + +6. **Initialize TinyUSB**: Add ``tusb_init()`` to your initialization code + +7. **Handle interrupts**: Call ``tusb_int_handler()`` from your USB IRQ handler + +8. **Run USB tasks**: Call ``tud_task()`` (device) or ``tuh_task()`` (host) periodically in your main loop + +9. **Implement class callbacks**: Implement callbacks for enabled USB classes + +Simple Integration Example +-------------------------- + +.. code-block:: c + + #include "tusb.h" + + int main(void) { + board_init(); // Your board initialization + + tusb_rhport_init_t dev_init = { + .role = TUSB_ROLE_DEVICE, + .speed = TUSB_SPEED_AUTO + }; + // tud_descriptor_* callbacks omitted here + tusb_init(0, &dev_init); + + while(1) { + tud_task(); // TinyUSB device task + your_application(); // Your application code + } + } + + void USB_IRQHandler(void) { + tusb_int_handler(0, true); + } + +.. 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. + +.. 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. + +Development Tips +================ + +**Debug builds and logging:** .. code-block:: bash - $ # make - $ make BOARD=feather_nrf52840_express all + $ make BOARD=stm32f407disco DEBUG=1 all # Debug build + $ make BOARD=stm32f407disco LOG=2 all # Enable detailed logging + +**CMake build system:** + +.. code-block:: bash - $ # cmake $ mkdir build && cd build - $ cmake -DBOARD=raspberry_pi_pico .. + $ cmake -DBOARD=stm32f407disco .. $ make -To list all available targets with cmake +**Alternative flash methods:** .. code-block:: bash - $ cmake --build . --target help + $ make BOARD=stm32f407disco flash-jlink # Use J-Link + $ make BOARD=stm32f407disco flash-openocd # Use OpenOCD + $ make BOARD=stm32f407disco all uf2 # Generate UF2 for drag-and-drop -Note: Some examples, especially those that use Vendor class (e.g., webUSB), may require udev permissions on Linux (and/or macOS) to access USB devices. It depends on your OS distribution, but typically copying ``99-tinyusb.rules`` and reloading udev is sufficient +**IAR Embedded Workbench:** -.. code-block:: bash - - $ cp examples/device/99-tinyusb.rules /etc/udev/rules.d/ - $ sudo udevadm control --reload-rules && sudo udevadm trigger - -RootHub Port Selection -~~~~~~~~~~~~~~~~~~~~~~ - -If a board has several ports, one port is chosen by default in the individual board.mk file. Use option ``RHPORT_DEVICE=x`` or ``RHPORT_HOST=x`` To choose another port. For example to select the HS port of a STM32F746Disco board, use: - -.. code-block:: bash - - $ make BOARD=stm32f746disco RHPORT_DEVICE=1 all - - $ cmake -DBOARD=stm32f746disco -DRHPORT_DEVICE=1 .. - -Port Speed -~~~~~~~~~~ - -An MCU can support multiple operational speeds. By default, the example build system uses the fastest speed supported by the board. Use the option ``RHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED/OPT_MODE_HIGH_SPEED`` or ``RHPORT_HOST_SPEED=OPT_MODE_FULL_SPEED/OPT_MODE_HIGH_SPEED``. For example, to force the F723 to operate at full speed instead of the default high speed: - -.. code-block:: bash - - $ make BOARD=stm32f746disco RHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED all - - $ cmake -DBOARD=stm32f746disco -DRHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED .. - -Size Analysis -~~~~~~~~~~~~~ - -First install `linkermap tool `_ then ``linkermap`` target can be used to analyze code size. You may want to compile with ``NO_LTO=1`` since ``-flto`` merges code across ``.o`` files and make it difficult to analyze. - -.. code-block:: bash - - $ make BOARD=feather_nrf52840_express NO_LTO=1 all linkermap - -Flashing the Device -^^^^^^^^^^^^^^^^^^^ - -The ``flash`` target uses the default on-board debugger (jlink/cmsisdap/stlink/dfu) to flash the binary. Please install the supporting software in advance. Some boards use bootloader/DFU via serial, which requires passing the serial port to the make command - -.. code-block:: bash - - $ make BOARD=feather_nrf52840_express flash - $ make SERIAL=/dev/ttyACM0 BOARD=feather_nrf52840_express flash - -Since jlink/openocd can be used with most of the boards, there is also ``flash-jlink/openocd`` (make) and ``EXAMPLE-jlink/openocd`` target for your convenience. Note for stm32 board with stlink, you can use ``flash-stlink`` target as well. - -.. code-block:: bash - - $ make BOARD=feather_nrf52840_express flash-jlink - $ make BOARD=feather_nrf52840_express flash-openocd - - $ cmake --build . --target cdc_msc-jlink - $ cmake --build . --target cdc_msc-openocd - -Some boards use UF2 bootloader for drag-and-drop into a mass storage device. UF2 files can be generated with the ``uf2`` target - -.. code-block:: bash - - $ make BOARD=feather_nrf52840_express all uf2 - - $ cmake --build . --target cdc_msc-uf2 - -Debugging -^^^^^^^^^ - -To compile for debugging add ``DEBUG=1``\ , for example - -.. code-block:: bash - - $ make BOARD=feather_nrf52840_express DEBUG=1 all - - $ cmake -DBOARD=feather_nrf52840_express -DCMAKE_BUILD_TYPE=Debug .. - -Enable Logging -~~~~~~~~~~~~~~ - -If you encounter issues running examples or need to submit a bug report, you can enable TinyUSB's built-in debug logging with the optional ``LOG=`` parameter. ``LOG=1`` prints only error messages, while ``LOG=2`` prints more detailed information about ongoing events. ``LOG=3`` or higher is not used yet. - -.. code-block:: bash - - $ make BOARD=feather_nrf52840_express LOG=2 all - - $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 .. - -Logging Performance Impact -~~~~~~~~~~~~~~~~~~~~~~~~~~ - -By default, log messages are printed via the on-board UART, which is slow and consumes significant CPU time compared to USB speeds. If your board supports an on-board or external debugger, it would be more efficient to use it for logging. There are 2 protocols: - - -* `LOGGER=rtt`: use `Segger RTT protocol `_ - - * Cons: requires jlink as the debugger. - * Pros: work with most if not all MCUs - * Software viewer is JLink RTT Viewer/Client/Logger which is bundled with JLink driver package. - -* ``LOGGER=swo``\ : Use dedicated SWO pin of ARM Cortex SWD debug header. - - * Cons: Only works with ARM Cortex MCUs except M0 - * Pros: should be compatible with more debugger that support SWO. - * Software viewer should be provided along with your debugger driver. - -.. code-block:: bash - - $ make BOARD=feather_nrf52840_express LOG=2 LOGGER=rtt all - $ make BOARD=feather_nrf52840_express LOG=2 LOGGER=swo all - - $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 -DLOGGER=rtt .. - $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 -DLOGGER=swo .. - -IAR Support -^^^^^^^^^^^ - -IAR Embedded Workbench is a commercial IDE and toolchain for embedded development. TinyUSB provides integration support for IAR through project connection files and native CMake support. - -Use project connection -~~~~~~~~~~~~~~~~~~~~~~ - -IAR Project Connection files are provided to import TinyUSB stack into your project. - -* A buildable project for your MCU needs to be created in advance. - - * Take example of STM32F0: - - - You need ``stm32f0xx.h``, ``startup_stm32f0xx.s``, and ``system_stm32f0xx.c``. - - - ``STM32F0xx_HAL_Driver`` is only needed to run examples, TinyUSB stack itself doesn't rely on MCU's SDKs. - -* Open ``Tools -> Configure Custom Argument Variables`` (Switch to ``Global`` tab if you want to do it for all your projects) - Click ``New Group ...``, name it to ``TUSB``, Click ``Add Variable ...``, name it to ``TUSB_DIR``, change it's value to the path of your TinyUSB stack, - for example ``C:\\tinyusb`` - -**Import stack only** - -Open ``Project -> Add project Connection ...``, click ``OK``, choose ``tinyusb\\tools\\iar_template.ipcf``. - -**Run examples** - -1. Run ``iar_gen.py`` to generate .ipcf files of examples: - - .. code-block:: - - > cd C:\tinyusb\tools - > python iar_gen.py - -2. Open ``Project -> Add project Connection ...``, click ``OK``, choose ``tinyusb\\examples\\(.ipcf of example)``. - For example ``C:\\tinyusb\\examples\\device\\cdc_msc\\iar_cdc_msc.ipcf`` - -Native CMake support -~~~~~~~~~~~~~~~~~~~~ - -With 9.50.1 release, IAR added experimental native CMake support (strangely not mentioned in public release note). Now it's possible to import CMakeLists.txt then build and debug as a normal project. - -Following these steps: - -1. Add IAR compiler binary path to system ``PATH`` environment variable, such as ``C:\Program Files\IAR Systems\Embedded Workbench 9.2\arm\bin``. -2. Create new project in IAR, in Tool chain dropdown menu, choose CMake for Arm then Import ``CMakeLists.txt`` from chosen example directory. -3. Set up board option in ``Option - CMake/CMSIS-TOOLBOX - CMake``, for example ``-DBOARD=stm32f439nucleo -DTOOLCHAIN=iar``, **Uncheck 'Override tools in env'**. -4. (For debug only) Choose correct CPU model in ``Option - General Options - Target``, to profit register and memory view. +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** @@ -294,65 +166,18 @@ Common Issues and Solutions * **Enumeration failure**: Enable logging with ``LOG=2`` and check for USB protocol errors * **Hard faults/crashes**: Verify interrupt handler setup and stack size allocation -Quick Start Examples --------------------- +**Linux Permissions** -Now that you have TinyUSB set up, you can try these examples to see it in action. - -Simple Device Example -^^^^^^^^^^^^^^^^^^^^^ - -The ``cdc_msc`` example creates a USB device with both a virtual serial port (CDC) and mass storage (MSC). This is the most commonly used example and demonstrates core device functionality. - -**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:** +Some examples require udev permissions to access USB devices: .. code-block:: bash - $ cd examples/device/cdc_msc - $ make BOARD=stm32f407disco all - $ make BOARD=stm32f407disco flash - -**Key files:** -* ``src/main.c`` - Main application with ``tud_task()`` loop -* ``src/usb_descriptors.c`` - USB device descriptors -* ``src/msc_disk.c`` - Mass storage implementation - -**Expected behavior:** Connect to your computer and you'll see both a new serial port and a small USB drive appear. - -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:** - -.. code-block:: bash - - $ cd examples/host/cdc_msc_hid - $ make BOARD=stm32f407disco all - $ make BOARD=stm32f407disco flash - -**Key files:** -* ``src/main.c`` - Main application with ``tuh_task()`` loop -* ``src/cdc_app.c`` - CDC host functionality -* ``src/msc_app.c`` - Mass storage host functionality -* ``src/hid_app.c`` - HID host functionality - -**Expected behavior:** Connect USB devices to see enumeration messages and device-specific interactions in the serial output. + $ cp `examples/device/99-tinyusb.rules `_ /etc/udev/rules.d/ + $ sudo udevadm control --reload-rules && sudo udevadm trigger Next Steps -^^^^^^^^^^ +========== * Check :doc:`reference/boards` for board-specific information -* Explore more examples in ``examples/device/`` and ``examples/host/`` directories +* Explore more examples in `examples/device/ `_ and `examples/host/ `_ directories +* Read :doc:`reference/usb_concepts` to understand USB fundamentals From 9dd67b19e207edd17917296a5c7c185c86507fa8 Mon Sep 17 00:00:00 2001 From: c1570 Date: Mon, 20 Oct 2025 20:19:40 +0200 Subject: [PATCH 09/13] revert unnecessary Sphinx config changes --- docs/conf.py | 20 -------------------- 1 file changed, 20 deletions(-) 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'] From 418239a2165551201ace6ddb49ce327c825e2607 Mon Sep 17 00:00:00 2001 From: c1570 Date: Mon, 20 Oct 2025 20:38:05 +0200 Subject: [PATCH 10/13] add missing class driver callbacks --- docs/reference/architecture.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/reference/architecture.rst b/docs/reference/architecture.rst index ab451a91a..8e4c6890e 100644 --- a/docs/reference/architecture.rst +++ b/docs/reference/architecture.rst @@ -199,6 +199,8 @@ All USB classes follow a similar architecture: Class Driver Interface ---------------------- +See ``usbd.c``. + **Required Functions**: - ``init()``: Initialize class driver - ``reset()``: Reset class state @@ -208,7 +210,9 @@ Class Driver Interface **Optional Functions**: - ``close()``: Clean up class resources -- ``sof_cb()``: Start-of-frame processing +- ``deinit()``: Deinitialize class driver +- ``sof()``: Start-of-frame processing +- ``xfer_isr()``: Called from USB ISR context on transfer completion. Data will get queued for ``xfer_cb()`` only if this returns ``false``. Descriptor Management --------------------- From 3cb248f2e59dade48e724946883a6f67de3680e4 Mon Sep 17 00:00:00 2001 From: c1570 Date: Mon, 20 Oct 2025 20:56:29 +0200 Subject: [PATCH 11/13] add note about CMake --- docs/getting_started.rst | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/getting_started.rst b/docs/getting_started.rst index 84663e486..a3d36a55c 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -7,7 +7,9 @@ This guide will get you up and running with TinyUSB quickly. We'll start with wo 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. +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. Simple Device Example --------------------- @@ -27,7 +29,7 @@ The `cdc_msc Date: Tue, 21 Oct 2025 14:09:00 +0200 Subject: [PATCH 12/13] use CMake in getting_started examples --- docs/getting_started.rst | 34 +++++++++------------------------- 1 file changed, 9 insertions(+), 25 deletions(-) diff --git a/docs/getting_started.rst b/docs/getting_started.rst index a3d36a55c..32c80b91c 100644 --- a/docs/getting_started.rst +++ b/docs/getting_started.rst @@ -27,11 +27,12 @@ The `cdc_msc Date: Tue, 11 Nov 2025 10:27:47 +0700 Subject: [PATCH 13/13] 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/faq.rst | 32 +---- docs/getting_started.rst | 191 ++++++++++++++------------ 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/{contributing => }/porting.rst | 0 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 +- 21 files changed, 413 insertions(+), 267 deletions(-) create mode 100644 docs/_static/custom.css delete mode 100644 docs/contributing/code_of_conduct.rst delete mode 100644 docs/contributing/index.rst create mode 100644 docs/info/code_of_conduct.rst create mode 100644 docs/integration.rst rename docs/{contributing => }/porting.rst (100%) 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 -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. +.. 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. + +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/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 - $ 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 + $ 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 + + $ cd examples/device/cdc_msc + $ 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 + $ cmake -DBOARD=stm32h743eval -B build + $ cmake --build build + +**Build and run with Make:** + +.. code-block:: bash + + $ cd examples/host/cdc_msc_hid + $ make BOARD=stm32h743eval all + $ make BOARD=stm32h743eval flash-jlink Connect USB devices to see enumeration messages and device-specific interactions in the serial output. -Project Structure ------------------ +Additional Build Options +------------------------ -TinyUSB separates example applications from board-specific hardware configurations: +Debug and Logging +^^^^^^^^^^^^^^^^^ -* **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 +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. -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 -============================ - -Once you've seen TinyUSB working, here's how to integrate it into your own project: - -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 all ``.c`` files from ``tinyusb/src/`` to your project - -3. **Configure include paths**: Add ``your_project/tinyusb/src`` to your include path. Ensure your include path contains ``tusb_config.h`` - -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 - -5. **Implement USB descriptors**: For device stack, implement all ``tud_descriptor_*_cb()`` callbacks - -6. **Initialize TinyUSB**: Add ``tusb_init()`` to your initialization code - -7. **Handle interrupts**: Call ``tusb_int_handler()`` from your USB IRQ handler - -8. **Run USB tasks**: Call ``tud_task()`` (device) or ``tuh_task()`` (host) periodically in your main loop - -9. **Implement class callbacks**: Implement callbacks for enabled USB classes - -Simple Integration Example --------------------------- - -.. code-block:: c - - #include "tusb.h" - - int main(void) { - board_init(); // Your board initialization - - tusb_rhport_init_t dev_init = { - .role = TUSB_ROLE_DEVICE, - .speed = TUSB_SPEED_AUTO - }; - // tud_descriptor_* callbacks omitted here - tusb_init(0, &dev_init); - - while(1) { - tud_task(); // TinyUSB device task - your_application(); // Your application code - } - } - - void USB_IRQHandler(void) { - tusb_int_handler(0, true); - } - -.. 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. - -.. 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. - -Development Tips -================ - -**Debug builds and logging:** +In addition to traditional hw uart as default, logging with debugger such as `Segger RTT `_ (10x faster) is also supported with `LOGGER=rtt` option. .. code-block:: bash - $ cmake -DBOARD=stm32f407disco -DDEBUG=1 ... # Debug build - $ cmake -DBOARD=stm32f407disco -DLOG=2 ... # Enable detailed logging + $ 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 -**IAR Embedded Workbench:** +.. code-block:: bash + + $ make BOARD=stm32h743eval LOG=2 all # logging level 2 with uart + $ make BOARD=stm32h743eval LOG=2 LOGGER=rtt all # logging level 2 with RTT + +RootHub Port Selection +^^^^^^^^^^^^^^^^^^^^^^ + +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: + +.. code-block:: bash + + $ cmake -B build -DBOARD=stm32h743eval -DRHPORT_DEVICE=1 # select roothub port 1 as device + +.. code-block:: bash + + $ make BOARD=stm32h743eval RHPORT_DEVICE=1 all # select roothub port 1 as device + +RootHub Port Speed +^^^^^^^^^^^^^^^^^^ + +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 + +.. code-block:: bash + + $ cmake -B build -DBOARD=stm32h743eval -DRHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED + +.. code-block:: bash + + $ make BOARD=stm32h743eval RHPORT_DEVICE_SPEED=OPT_MODE_FULL_SPEED all + + +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/contributing/porting.rst b/docs/porting.rst similarity index 100% rename from docs/contributing/porting.rst rename to docs/porting.rst 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 - ┌─────────────────────────────────────────┐ - │ 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 - └─────────────────────────────────────────┘ +.. raw:: html + +
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 () + family_resolve_board("${BOARD}" BOARD_PATH) - # 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 () - - # 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')} """