diff options
| author | c1570 <[email protected]> | 2025-09-26 18:34:10 +0200 |
|---|---|---|
| committer | c1570 <[email protected]> | 2025-10-20 21:07:31 +0200 |
| commit | 39e2e5167c3b59176293023eaf0249a5b3955f0c (patch) | |
| tree | 810fe7f163442b775368623ffaef56b9a7bc9208 /docs | |
| parent | a332acf5ead28089c732428a4254354baec9afd6 (diff) | |
improved getting_started, integrated "first device/host"
Diffstat (limited to 'docs')
| -rw-r--r-- | docs/explanation/usb_concepts.rst | 6 | ||||
| -rw-r--r-- | docs/faq.rst | 2 | ||||
| -rw-r--r-- | docs/guides/index.rst | 10 | ||||
| -rw-r--r-- | docs/guides/integration.rst | 494 | ||||
| -rw-r--r-- | docs/reference/glossary.rst | 3 | ||||
| -rw-r--r-- | docs/tutorials/first_device.rst | 151 | ||||
| -rw-r--r-- | docs/tutorials/first_host.rst | 160 | ||||
| -rw-r--r-- | docs/tutorials/getting_started.rst | 176 | ||||
| -rw-r--r-- | docs/tutorials/index.rst | 4 |
9 files changed, 126 insertions, 880 deletions
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,8 +151,36 @@ First install `linkermap tool <https://github.com/hathach/linkermap>`_ then ``li $ make BOARD=feather_nrf52840_express NO_LTO=1 all linkermap -Debug -^^^^^ +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 @@ -160,10 +190,10 @@ To compile for debugging add ``DEBUG=1``\ , for example $ cmake -DBOARD=feather_nrf52840_express -DCMAKE_BUILD_TYPE=Debug .. -Log -~~~ +Enable Logging +~~~~~~~~~~~~~~ -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. +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 @@ -171,10 +201,10 @@ Should you have an issue running example and/or submitting an bug report. You co $ cmake -DBOARD=feather_nrf52840_express -DLOG=2 .. -Logger -~~~~~~ +Logging Performance Impact +~~~~~~~~~~~~~~~~~~~~~~~~~~ -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: +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 <https://www.segger.com/products/debug-probes/j-link/technology/about-real-time-transfer/>`_ @@ -183,9 +213,9 @@ By default log message is printed via on-board UART which is slow and take lots * 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. +* ``LOGGER=swo``\ : Use dedicated SWO pin of ARM Cortex SWD debug header. - * Cons: only work with ARM Cortex MCUs minus M0 + * 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. @@ -197,49 +227,23 @@ By default log message is printed via on-board UART which is slow and take lots $ 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 - -.. 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 board use uf2 bootloader for drag & drop in to mass storage device, uf2 can be generated with ``uf2`` target - -.. code-block:: bash - - $ make BOARD=feather_nrf52840_express all uf2 - - $ cmake --build . --target cdc_msc-uf2 - 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 +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 |
