Electronics Guide

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-20 Gbps) modes introduced additional signal pairs for simultaneous bidirectional communication. While offering substantial bandwidth improvements, USB 3.x requires more complex PHY implementations.

USB4: Built on Thunderbolt 3 technology, USB4 delivers up to 40 Gbps with tunneling capabilities for multiple protocols. Embedded implementations remain limited due to hardware complexity.

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. OTG uses a micro-AB receptacle and ID pin to detect cable orientation and determine initial roles.

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: Numeric identifiers that uniquely identify the device. Legitimate vendor IDs require USB-IF membership; development often uses shared testing VID/PID pairs.

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 device and host functionality. Its clean architecture and active development make it popular for new designs.

STM32 USB libraries: ST provides USB device and host libraries for their STM32 microcontrollers, integrated with their HAL and CubeMX tools.

NXP USB stack: Comprehensive USB support for NXP microcontrollers, including LPC and Kinetis families.

LUFA: Lightweight USB Framework for AVR microcontrollers, notable for extensive documentation and example implementations.

Commercial stacks: Vendors like Segger, Micrium, and Express Logic 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 derived from crystal oscillators. Full-speed and higher require 48 MHz or higher clock accuracy within specified tolerances. Some controllers can calibrate internal oscillators from USB frames, relaxing crystal requirements.

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 current limits (100 mA unconfigured, up to 500 mA configured for USB 2.0). Soft-start circuits prevent inrush current violations.

Self-powered devices: Devices with their own power supply still must handle VBUS detection for proper USB operation and may optionally draw limited current from the bus.

USB Power Delivery: USB PD enables power negotiation up to 240W over USB Type-C connections. Implementing USB PD requires additional controller hardware and protocol implementation.

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-based analyzers provide basic functionality while hardware analyzers capture at full speed without affecting 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.