Universal Serial Bus
Universal Serial Bus (USB) has become the dominant peripheral interface standard, connecting billions of devices ranging from keyboards and storage drives to sophisticated medical instruments and industrial controllers. For embedded systems developers, USB provides a standardized, widely supported mechanism for device connectivity, enabling products to interface seamlessly with computers, smartphones, and other USB hosts.
Implementing USB in embedded systems requires understanding the protocol architecture, hardware requirements, and software stack components that together enable reliable USB communication. This article explores USB fundamentals from an embedded systems perspective, covering device classes, operating modes, and the practical aspects of USB driver development.
USB Protocol Fundamentals
USB operates on a hierarchical, host-controlled architecture where a single host manages communication with multiple devices. Understanding this architecture is essential for implementing USB functionality in embedded systems.
Physical Layer
USB uses differential signaling on a twisted pair of data lines (D+ and D-) along with power (VBUS) and ground connections. The standard has evolved through several generations, each increasing data rates while maintaining backward compatibility:
USB 1.x: Low Speed (1.5 Mbps) and Full Speed (12 Mbps) modes established the foundational protocol. Low Speed remains common for simple human interface devices where minimal bandwidth suffices.
USB 2.0: High Speed mode (480 Mbps) dramatically increased bandwidth, enabling mass storage, video, and other data-intensive applications. USB 2.0 remains prevalent in embedded systems due to mature silicon support and adequate performance for many applications.
USB 3.x: SuperSpeed (5 Gbps) and SuperSpeed+ (10 and 20 Gbps) modes added a second differential signaling path so that data can flow in both directions simultaneously, alongside the retained USB 2.0 wires for backward compatibility. The higher bandwidth comes at the cost of more complex PHY implementations.
USB4: Built on the Thunderbolt 3 protocol, USB4 carries multiple tunneled protocols (USB 3.2, DisplayPort, and optionally PCI Express) over a single Type-C link. The original USB4 specification (2019) reaches 40 Gbps; USB4 Version 2.0 (published 2022) raises the symmetric rate to 80 Gbps using PAM-3 signaling, with an optional asymmetric mode reaching 120 Gbps in one direction. Embedded implementations remain limited because USB4 demands high-speed silicon and Type-C connectors.
Protocol Architecture
USB communication occurs through a layered protocol stack with well-defined responsibilities at each level:
Transaction layer: Defines the packet types (token, data, handshake) and transaction sequences that form the basis of all USB communication. The host initiates all transactions, with devices responding according to protocol rules.
Endpoint model: Each USB device presents one or more endpoints representing logical communication channels. Endpoint 0 is mandatory and handles device configuration. Additional endpoints support application-specific data transfer.
Transfer types: USB defines four transfer types optimized for different communication patterns: control transfers for configuration, bulk transfers for large data blocks, interrupt transfers for small periodic data, and isochronous transfers for time-sensitive streaming.
Descriptor hierarchy: Devices describe their capabilities through a hierarchy of descriptors that hosts read during enumeration. Device, configuration, interface, and endpoint descriptors collectively define how the device operates and what drivers it requires.
Enumeration Process
When a USB device connects, the host conducts an enumeration sequence to identify and configure the device:
The host first resets the device and reads its device descriptor to obtain basic identification including vendor ID, product ID, and supported USB version. Configuration descriptors reveal available configurations and their power requirements. The host selects a configuration and may further configure individual interfaces.
Successful enumeration results in driver binding, where appropriate host software assumes responsibility for device communication. Failed enumeration typically appears to users as an unrecognized device, often indicating descriptor problems or electrical issues.
USB Device Classes
USB device classes define standardized functionality enabling operating systems to use generic drivers for entire categories of devices. Implementing a standard class simplifies development by leveraging existing host drivers rather than requiring custom software.
Human Interface Device Class
The HID class covers keyboards, mice, game controllers, and various input devices. HID's report descriptor mechanism provides remarkable flexibility, allowing devices to define custom data formats interpreted generically by HID drivers.
Embedded systems commonly use HID for control panels, custom input devices, and surprisingly, for generic data transfer when avoiding custom driver installation is important. HID's universal driver support across operating systems makes it attractive despite bandwidth limitations.
Mass Storage Class
USB Mass Storage Class (MSC) presents devices as block storage accessible through standard filesystem interfaces. Flash drives, external hard drives, and card readers implement MSC to appear as standard storage volumes.
Embedded implementations typically use the Bulk-Only Transport (BOT) protocol with SCSI command sets. The device presents logical units containing block storage that hosts can format and use like any disk. This class requires implementing block device abstraction over whatever physical storage medium the embedded system provides.
Communication Device Class
CDC encompasses several subclasses for communication devices. The Abstract Control Model (ACM) subclass emulates serial ports, providing virtual COM port functionality over USB. This approach proves invaluable for embedded systems requiring debug consoles, configuration interfaces, or legacy serial protocol support.
The Ethernet Control Model (ECM) and Network Control Model (NCM) subclasses enable network connectivity, allowing embedded devices to appear as network adapters. These prove useful for devices requiring IP connectivity without dedicated Ethernet hardware.
Audio and Video Classes
The USB Audio Class supports microphones, speakers, mixers, and other audio equipment using isochronous transfers for time-sensitive audio streaming. Video Class handles webcams and video capture devices with similar streaming requirements.
Implementing these classes in embedded systems requires careful attention to isochronous endpoint management and audio/video encoding. The complexity typically limits implementation to specialized audio or video applications.
Vendor-Specific Implementations
When standard classes prove inadequate, vendor-specific implementations offer complete flexibility at the cost of requiring custom host drivers. Vendor class devices use proprietary protocols defined by the device manufacturer.
Cross-platform compatibility becomes the developer's responsibility with vendor-specific implementations. Libraries like libusb provide user-space USB access on various operating systems, simplifying custom driver development while avoiding kernel-mode programming.
Host and Device Modes
USB defines distinct roles for hosts and devices, with significant implications for embedded system implementations.
Device Mode Implementation
Most embedded USB implementations operate in device mode, presenting the embedded system as a peripheral to a host computer or smartphone. Device mode requires:
USB device controller: Hardware implementing the USB device protocol, including PHY, protocol engine, and endpoint buffers. Many microcontrollers integrate USB device controllers, simplifying hardware design.
Device stack: Software managing controller hardware, endpoint state, and providing class or application interfaces. Commercial and open-source USB device stacks abstract hardware differences and implement standard class functionality.
Descriptor configuration: Properly structured descriptors enabling host enumeration. Incorrect descriptors cause enumeration failures and non-functional devices.
Device mode implementation is generally simpler than host mode because the device responds to host-initiated transactions rather than managing the bus.
Host Mode Implementation
Host mode enables embedded systems to control USB peripherals, accessing storage devices, communicating with sensors, or interfacing with standard USB equipment. Host mode requires:
USB host controller: Hardware capable of generating USB transactions, managing bus timing, and handling the electrical requirements of powering attached devices. Host controllers are more complex than device controllers and less commonly integrated in microcontrollers.
Host stack: Software implementing enumeration, hub management, and providing interfaces for device class drivers. Host stacks must handle the complexity of arbitrary device attachment and support required device classes.
Class drivers: Software implementing communication protocols for attached device classes. The host must include drivers for every device class it needs to support.
Host mode substantially increases complexity compared to device mode. The host must manage power delivery, handle device attachment and removal events, and coordinate multiple potentially simultaneous device communications.
USB On-The-Go
USB On-The-Go (OTG) enables devices to operate as either host or device, with role determination occurring at connection time. Legacy OTG used a micro-AB receptacle and a sense (ID) pin to detect cable orientation and assign initial roles. On USB Type-C systems, this function moves to the configuration channel (CC) pins, where pull-up and pull-down resistors signal whether a port behaves as a source (host) or sink (device); Dual-Role Port (DRP) implementations alternate these resistors until a role is established.
Dual-role device: OTG devices implement both host and device stacks, switching between them based on connection context. This enables scenarios like a camera that connects as a device to computers but as a host to printers.
Host Negotiation Protocol: OTG allows connected devices to request role swapping through HNP, enabling the device currently in peripheral role to request host functionality.
Session Request Protocol: SRP allows devices to request the host to provide power and begin a session, useful for power management in battery-operated equipment.
OTG implementation requires hardware supporting both modes and software managing role transitions. The additional complexity is justified when applications genuinely require both host and device functionality.
USB Driver Development
Developing USB drivers for embedded systems involves working with USB stacks that abstract hardware details while exposing necessary functionality for application development.
Device Stack Architecture
USB device stacks typically organize into layers with defined responsibilities:
Controller driver: The lowest layer interfaces directly with USB controller hardware, managing registers, DMA, and interrupts. This layer is specific to the controller silicon.
Core stack: Implements USB protocol logic including endpoint management, standard request handling, and state machine management. The core stack provides hardware-independent interfaces used by class implementations.
Class drivers: Implement specific device class functionality, translating between USB protocols and application interfaces. Class drivers for standard classes like HID, MSC, and CDC follow USB-IF specifications.
Application interface: Provides the API that application code uses to send and receive data, configure device behavior, and respond to USB events.
Descriptor Design
USB descriptors form the device's identity and determine how hosts interact with it. Descriptor design decisions include:
Vendor and product IDs: Sixteen-bit numeric identifiers that together identify a product. A registered vendor ID (VID) requires USB-IF membership; for hobby and open-source work, the pid.codes registry issues product IDs under the community-allocated VID 0x1209, and silicon vendors sometimes permit limited use of their VID for products built on their parts. Shipping a product under another company's VID without permission risks driver conflicts and policy violations.
Configuration structure: Devices can offer multiple configurations with different power requirements or functionality. Most embedded devices need only a single configuration.
Interface organization: Interfaces represent functional units within a configuration. Composite devices combine multiple interfaces, such as CDC-ACM paired with MSC, allowing a single device to provide multiple capabilities.
Endpoint allocation: Endpoint types and sizes must match application requirements while respecting controller limitations. Endpoint configuration significantly impacts throughput and latency.
Data Transfer Management
Efficient data transfer implementation is crucial for USB driver performance:
Buffer management: USB controllers often require specific buffer alignment and location. Double buffering techniques help maintain throughput by preparing the next transfer while the current one completes.
Flow control: USB protocol provides implicit flow control through NAK handshakes when devices cannot accept or provide data. Drivers must handle backpressure gracefully without losing data or blocking indefinitely.
Error handling: USB includes CRC checking and retry mechanisms, but drivers must still handle errors that persist beyond hardware recovery. Proper error reporting and recovery procedures prevent system hangs and data corruption.
Power management: USB suspend and resume events require appropriate driver responses. Devices should reduce power consumption during suspend and restore operation promptly upon resume.
Common USB Stacks
Several USB stacks serve embedded development needs:
TinyUSB: An open-source stack supporting numerous microcontrollers with both device and host functionality. Its clean architecture, permissive MIT license, and active development make it popular for new designs, including the Raspberry Pi RP2040 and RP2350.
STM32 USB libraries: ST provides USB device and host middleware for its STM32 microcontrollers, integrated with the STM32Cube HAL and the STM32CubeMX/CubeIDE configuration tools.
NXP USB stack: Comprehensive USB support for NXP microcontrollers, including the LPC and Kinetis families, distributed through the MCUXpresso SDK.
LUFA: Lightweight USB Framework for AVR microcontrollers, notable for extensive documentation and example implementations.
Eclipse ThreadX USBX: A full-featured device and host stack (formerly Azure RTOS USBX, and before that Express Logic) now developed as open source under the Eclipse Foundation.
Commercial stacks: Vendors such as SEGGER (emUSB) and others offer commercial USB stacks with support contracts, certification assistance, and guaranteed performance characteristics.
Hardware Considerations
USB implementation requires attention to hardware design aspects that affect reliability, compliance, and performance.
PHY Integration
The USB physical layer (PHY) handles electrical signaling and may be integrated or external to the microcontroller:
Integrated PHY: Many microcontrollers include USB PHY circuitry, simplifying design but potentially limiting flexibility. Integrated PHYs typically support USB 2.0 speeds.
External PHY: High-speed and USB 3.x implementations often require external PHY chips connected via ULPI or similar interfaces. External PHYs offer better signal quality and advanced features at increased cost and complexity.
Oscillator requirements: USB requires precise timing, conventionally derived from a crystal that yields a 48 MHz reference. The specification sets tight frequency tolerances (roughly ±0.25% for Full Speed and ±500 ppm for High Speed), which a standard quartz crystal meets easily but most uncalibrated internal RC oscillators do not. Some controllers recover the clock from the host's USB traffic, enabling crystal-less Full-Speed designs; High Speed and USB 3.x generally still require a precise external reference.
PCB Layout Guidelines
USB signal integrity depends on proper PCB design:
Differential pair routing: D+ and D- lines should be routed as a matched differential pair with controlled impedance (90 ohms differential for USB 2.0). Length matching ensures signal timing alignment.
Connector placement: USB connectors should be placed near board edges with short traces to the controller. ESD protection devices should be located close to connectors.
Ground plane integrity: Solid ground planes beneath USB traces reduce noise and maintain impedance control. Avoid routing traces across ground plane gaps.
EMI considerations: USB can both emit and receive electromagnetic interference. Proper shielding, filtering, and layout techniques minimize EMI issues that could cause compliance failures.
Power Requirements
USB power delivery involves multiple considerations:
Bus-powered devices: Devices drawing power from VBUS must respect the limits negotiated during enumeration. A USB 2.0 device may draw up to one unit load (100 mA) before configuration and up to five unit loads (500 mA) once configured; USB 3.x raises the configured limit to 900 mA. A device must request only what its configuration descriptor declares, and soft-start circuits help keep inrush current within the allowed bounds.
Self-powered devices: Devices with their own power supply still must monitor VBUS to detect host presence and connect their data-line pull-up only when the host is powered, and they may optionally draw limited current from the bus.
USB Power Delivery: USB PD negotiates higher voltages and currents over USB Type-C. The PD 3.1 Extended Power Range (EPR) tops out at 240 W (48 V at 5 A), well above the 100 W (20 V at 5 A) ceiling of earlier PD revisions. Implementing USB PD requires a dedicated PD controller and protocol stack that communicate over the Type-C CC line.
Testing and Compliance
USB devices undergo various testing levels to ensure reliable operation and interoperability.
Development Testing
During development, various tools help verify correct operation:
USB analyzers: Protocol analyzers capture and decode USB traffic, invaluable for debugging enumeration problems, timing issues, and protocol errors. Software tracers such as Wireshark with usbmon (Linux) or USBPcap (Windows) decode traffic as the host sees it, while inline hardware analyzers (for example, those from Total Phase or Teledyne LeCroy) sit on the wire and capture at full speed without disturbing bus timing.
Compliance checkers: Software tools verify descriptor structure and content against USB specifications, catching common errors before they cause enumeration failures.
Operating system logs: Host operating systems log enumeration events and errors, providing diagnostic information accessible without specialized hardware.
USB-IF Certification
Official USB certification through the USB Implementers Forum verifies specification compliance and grants use of USB logos:
Compliance testing: USB-IF authorized test labs conduct electrical, protocol, and interoperability testing according to defined test specifications. Tests verify signal quality, timing, descriptor correctness, and proper class implementation.
Certification benefits: Certified products can display USB logos, providing customer confidence and demonstrating interoperability. Some host manufacturers require certification for compatibility claims.
Vendor ID assignment: USB-IF membership includes vendor ID assignment necessary for unique product identification. Using unassigned vendor IDs violates USB-IF policy and risks conflicts with legitimate assignees.
Best Practices
Experience with USB implementations has revealed several best practices for reliable operation:
Start with working examples: USB stack vendors provide example implementations for common device classes. Starting from working examples and modifying incrementally reduces debugging time compared to implementing from scratch.
Validate descriptors early: Descriptor errors cause enumeration failures that can be difficult to diagnose. Validate descriptor structures with compliance checking tools before debugging electrical or firmware issues.
Handle all standard requests: Even when using USB stacks, verify that all standard requests defined in the USB specification receive appropriate responses. Missing handlers for optional requests can cause compatibility problems with specific hosts.
Test with multiple hosts: Different operating systems and USB host controllers exhibit varying behaviors. Test with Windows, macOS, and Linux hosts, as well as different host controller manufacturers, to ensure broad compatibility.
Implement robust error recovery: USB connections can experience transient errors, cable disconnections, and host resets. Firmware should handle these conditions gracefully, recovering to functional operation without requiring power cycles.
Consider certification requirements early: If USB-IF certification is needed, design decisions made early in development affect certification success. Understanding test requirements before design freeze prevents costly redesigns.
Summary
USB provides embedded systems with a standardized, universally supported interface for device connectivity. Successful USB implementation requires understanding the protocol architecture, selecting appropriate device classes, implementing robust driver software, and attending to hardware design details that affect compliance and reliability.
The choice between standard device classes and vendor-specific implementations depends on application requirements and acceptable development effort. Standard classes offer broad compatibility through existing drivers, while vendor-specific implementations provide complete flexibility at the cost of custom host software.
Whether implementing simple HID devices or sophisticated composite configurations with multiple interfaces, the principles of proper descriptor design, efficient data transfer management, and thorough testing apply universally. As USB continues evolving with higher speeds and expanded power delivery capabilities, embedded systems developers must balance adopting new features against implementation complexity and silicon availability.
Related Topics
- Serial Communication Protocols - UART, SPI, and I2C interfaces that USB often replaces or supplements at the board level.
- Controller Area Network - a robust differential bus for automotive and industrial nodes, contrasting with USB's host-centric model.
- Ethernet and Industrial Protocols - networked connectivity that USB CDC-ECM and CDC-NCM can bridge to.
- Wireless Communication Interfaces - radio links that complement or replace wired USB connections.
- Parallel Interfaces - wide-bus alternatives for high-throughput, short-distance connections.
- Power Management - bus-powered and USB Power Delivery design considerations for embedded products.