WIP improved docs (feat. LLM)

This commit is contained in:
c1570
2025-09-22 23:31:13 +02:00
parent 79445c2386
commit e4ff88f364
19 changed files with 2825 additions and 31 deletions

View File

@ -24,9 +24,29 @@ extensions = [
'sphinx.ext.autodoc', 'sphinx.ext.autodoc',
'sphinx.ext.intersphinx', 'sphinx.ext.intersphinx',
'sphinx.ext.todo', 'sphinx.ext.todo',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
'sphinx_autodoc_typehints', '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'] templates_path = ['_templates']
exclude_patterns = ['_build'] exclude_patterns = ['_build']

View File

@ -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

View File

@ -0,0 +1,11 @@
***********
Explanation
***********
Deep understanding of TinyUSB's design, architecture, and concepts.
.. toctree::
:maxdepth: 2
architecture
usb_concepts

View File

@ -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

210
docs/faq.rst Normal file
View File

@ -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.

10
docs/guides/index.rst Normal file
View File

@ -0,0 +1,10 @@
**********
How-to Guides
**********
Problem-solving guides for common TinyUSB development tasks.
.. toctree::
:maxdepth: 2
integration

494
docs/guides/integration.rst Normal file
View File

@ -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

View File

@ -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:: .. toctree::
:caption: Index :maxdepth: 2
:hidden: :caption: Learning
Info <info/index> tutorials/index
Reference <reference/index>
Contributing <contributing/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:: .. toctree::
:caption: External Links :caption: External Links

View File

@ -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. 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 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 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 Class Drivers
------------- -------------
@ -38,5 +38,5 @@ Much of the processing of the USB stack is done in an interrupt context, and car
In particular: 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. * 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``. * All defined global variables are marked as ``static``.

View File

@ -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``.

View File

@ -2,7 +2,7 @@
Dependencies 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 Local Path Repo Commit Required by

View File

@ -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.

View File

@ -1,10 +1,16 @@
Index *********
===== Reference
*********
Complete reference documentation for TinyUSB APIs, configuration, and supported hardware.
.. toctree:: .. toctree::
:maxdepth: 2 :maxdepth: 2
getting_started api/index
configuration
usb_classes
boards boards
dependencies dependencies
concurrency concurrency
glossary

View File

@ -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

318
docs/troubleshooting.rst Normal file
View File

@ -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

View File

@ -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`

View File

@ -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`

View File

@ -2,20 +2,22 @@
Getting Started 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 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`` * Copy or ``git submodule`` this repository 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 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 also contains the configuration file ``tusb_config.h``. * 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 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). * 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 need. Ultimately you need to implement all **tud descriptor** callbacks for the stack to work. * 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 ``tusb_init(rhport, role)`` call to your reset initialization code. * 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)`` in your USB IRQ handler
* Implement all enabled classes's callbacks. * Implement all enabled classes' 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. * 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 .. 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 $ git clone https://github.com/hathach/tinyusb tinyusb
$ cd 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 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 .. code-block:: bash
$ python tools/get_deps.py rp2040 $ 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 .. 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 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 .. 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. 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'**. 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. 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

12
docs/tutorials/index.rst Normal file
View File

@ -0,0 +1,12 @@
*********
Tutorials
*********
Step-by-step learning guides for TinyUSB development.
.. toctree::
:maxdepth: 2
getting_started
first_device
first_host