A quick look at USB. For more info see Jan Axelson's wonderful site: www.lvr.com
Published in ESP, 2000
For novel ideas about building embedded systems (both hardware and firmware), join the 27,000+ engineers who subscribe to The Embedded Muse, a free biweekly newsletter. The Muse has no hype and no vendor PR. It takes just a few seconds (just enter your email, which is shared with absolutely no one) to subscribe.
By Jack Ganssle
An Introduction to Developing USB Apps
The Universal Serial Bus (USB) was born of the frustration PC users experience trying to connect an incredibly diverse range of peripherals to their computers. It's the child of vendors whose laptops require a small profile peripheral connector. It further promises to reduce the proliferation of cables and wall transformers that overwhelm even the smallest computer installation.
USB above all offers users simple connectivity. It eliminates the vast mix of different connectors for printers, keyboards, mice and other peripherals. In a USB environment there are no DIP switches for setting peripheral addresses and IRQs. It supports all kinds of data, from slow mouse inputs to digitized audio and compressed video.
Perhaps USB seems an inappropriate topic for Embedded Systems Programming magazine. Why would embedded folks care about something as PC-centric as this? Fact is, every USB device is an embedded system. If you're building an application that connects to a PC, realize that USB is supplanting old-fashioned parallel and serial interfaces. Sooner or later you'll have to migrate from RS-232 to USB.
USB is a serial protocol and physical link, which transmits all data differentially on a single pair of wires. Another pair provides power to downstream peripherals.
The standard specifies two kinds of cables and two variations of connectors. High speed cables, for 12 Mbs communication, are better shielded than their less expensive 1.5 Mbs counterparts. Each cable has an "A" connector on one end and a "B" on the other. Figure 1 shows that "A" connectors go to the upstream connection while the "B" version attaches downstream. Since the two types are physically different it's impossible to install a cable incorrectly.
Cable lengths are limited to 5 meters for 12 Mbs connections and 3 meters for 1.5 Mbs. This sounds backwards, but stems from the use of better cables at higher speeds.
USB's topology is a "tiered star" (see figure 1). Hubs are the communication nodes that interconnect devices. One, and only one, "host" device (typically a PC) includes the "root hub" which forms the nexus for all device connections. The host is the USB system's master, and as such controls and schedules all communications activities.
Peripherals, the devices controlled by USB, are slaves responding to commands from the host. When a peripheral is attached to the USB network, the host communicates with the device to learn its identity and to discover which device driver is required (a process called "enumeration"). To avoid DIP switch and IRQ headaches of the past, during enumeration the host supplies a device address to the peripheral.
The spec recognizes two kinds of peripherals: stand-alone (single function units, like a mouse) or compound devices (those that have more than one peripheral sharing a USB port - say a video camera with separate audio processor).
Hubs are bridges; they increase the logical and physical fan-out of the network. A hub has a single upstream connection (that going to the root hub, or the next hub closer to the root), and one to many downstream connections.
Hubs are themselves USB devices, and may incorporate some amount of intelligence. A critical part of the philosophy of USB is that users may connect and remove peripherals without powering the entire system down. Hubs detect these topology changes. They also source power to the USB network; power can come from the hub itself (if it has a built-in power supply), or can be passed through from an upstream hub.
Once a hub detects a new peripheral (or one that has just been removed), reports the new information to the host, and enables comm with a newly inserted device, it essentially becomes invisible, emulating a smart wire, passing data between the host and the devices. Though physically configured as a tiered star, logically, to the application code, there's a direct connection between the host and each device.
USB Comm Overview
USB communications takes place between the host and endpoints located in the peripherals. An endpoint is a uniquely addressable portion of the peripheral that is the source or receiver of data. 4 bits define the device's endpoint address, codes also indicate transfer direction and whether the transaction is a "control" transfer. Endpoint 0 is reserved for control transfers, giving 15 bi-directional destinations or sources of data within a device.
The idea of endpoints leads to an important concept in USB transactions, that of the pipe. All transfers occur through virtual pipes that connect the peripheral's endpoints with the host. When establishing communications with the peripheral, each endpoint returns a descriptor, a data structure that tells the host about the endpoint's configuration and expectations. Descriptors include transfer type, max size of data packets, perhaps the interval for data transfers, and in some cases the bandwidth needed. Give this data the host establishes connections to the endpoints through virtual pipes, which even have a size (bandwidth), making them analogous to household plumbing.
USB supports four data transfer types: control, isochronous, bulk, and interrupt.
Control transfers exchange configuration, setup and command information between the device and the host. CRCs check the data; retransmissions when needed guarantees the correctness of these packets.
Bulk transfers move large amounts of data when timely delivery isn't critical. Typical applications include printers and scanners. Bulk transfers are fillers, claiming unused USB bandwidth when nothing more important is going on. CRCs protect these packets.
Interrupt transfers, though not interrupts in the CPU-diverting sense, poll devices to see if they need service. Peripherals exchanging small amounts of data which need immediate attention (mice, keyboards) use interrupt transfers. Error checking validates the data.
Finally, isochronous transfers handle streaming data like that from an audio or video device. It's time sensitive information so, within limitations, it has guaranteed access to the USB bus. No error checking occurs so the system must tolerate occasional scrambled bytes.
The Host Device Driver
The benevolent days of simple interfaces like RS-232 are long gone! as are the frustrations of making incompatible devices talk reliably. USB is a very complex standard that requires an enormous amount of software support, both on the firmware side and in the host computer.
Most host-end connections, for better or worse, will be PCs running a Microsoft operating system. There is no USB support at all in DOS or Windows 3.x. Windows 95 provided some USB drivers, though only in the later versions starting with OEM Software Release 2.1. All Windows 98 releases include a full set of drivers for common USB applications.
Some of the most brilliant firmware engineers quail at the thought of writing Windows drivers, with good reasons. Unhappily, a USB driver is a difficult beast. The good news is that in many cases the drivers provided with Windows will handle even your custom peripheral. Let's look at how Windows drivers function.
Microsoft's roadmap for drivers in Windows 98 and beyond relies on the Win 32 Driver Model (WDM), which layers different parts of the communications process into a stack of drivers (see figure 2). Application code (via Windows API calls) communicates with class or custom drivers in the WDM. Within the WDM stack itself data transfers use lower-level IRP (I/O Request Packets) rather than API calls.
The low level USB bus driver manages USB device power, enumeration, and various USB transactions. Below this, the Host Controller Driver talks directly to the USB hardware in the PC. Both of these drivers are supplied with current Windows versions; you won't have to write or modify either.
Windows, as well as the USB specification, segments drivers into "classes", where hardware that falls into a single class shares similar interfaces. A class defines a baseline specification for a given set of capabilities; all devices in a class require comparable types of software support.
An example is the Human Interface Device (HID class), which supports devices like mice, joysticks, and keyboards. Another is the Monitor class, which controls image position, size, and alignment on video displays. Windows ships with a complete HID class driver! so if your peripheral requires HID-like support, you may be able to use this built-in driver without writing any host code.
Current specifications of class drivers may be found on the USB home page (www.usb.org); Windows support of these is of course available from Microsoft, but at this time is somewhat limited (though HID-class devices are indeed fully supported).
Custom drivers are an alternative to class drivers. A custom driver exploits the capabilities of a particular bit of hardware at the end of the USB cable. If you've built a data acquisition system, for example, odds are there's no class driver easily available so you'll have to write your own - a daunting task. Similarly, if your device has capabilities well beyond that of a standard class you may also have to write a custom driver to support these features.
BlueWater Systems (www.bluewatersystems.com) also has a driver development kit whose wizard greatly eases any sort of Windows driver development. An add-on, the USB Extensions Toolkit, is a boon for USB drivers, but be aware there's a per-unit royalty charge.
Unless you're building a typically PC-centric peripheral like a mouse, you'll likely also create a host application that exchanges data with the USB device and interacts with the user. An oscilloscope, say, using an A/D converter and triggering logic located at the end of a USB cable, requires an application with a scope-like GUI. To exchange data with the USB device the application code simply issues standard file-like API calls, using a standard Windows handle to identify the device.
Since USB is (for all practical purposes) tied to the high-volume PC business, dozens of vendors offer hundreds of different support chips.
USB parts are rather hard to categorize, but fall generally into 3 camps: host-side USB controllers (which live inside the PC, and are probably of little interest to Embedded Systems Programming readers), devices designed as stand-alone USB peripheral controllers (like a very smart UART, these chips handle comm but you'll need another microprocessor as the brains of your device), and versions of popular processors that include a USB interface. Using the UART metaphor again, this last group is like the high integration CPU with an on-board UART; both your application code and that needed for USB control runs on the same part.
Beyond these three categories some vendors offer specialized parts, such as USB camera controllers, audio devices, bridges that link USB to other busses, and specialized HID controllers.
It's impossible to do justice to various products here. Here's a few highlights:
Cypress (www.cypress.com) has a variety of high and low speed chips based on 8 bit RISC cores with instruction sets optimized for USB applications. Both one time programmable and EPROM parts are available. Their development kits (the starter kit costs $99, but the much more useful developer's kit runs a still-reasonable $495) are the way to go for getting firmware running.
Scanlogic's SL16-USB controller (www.scanlogic.com) is a custom-architecture 12 Mbs controller. Their development board, like most of those offered by other vendors, includes WDM drivers. Interestingly, Scanlogic claims users can bring an embedded USB app up in only 5 weeks (on their hardware, of course).
Philips' PDIUSBD11 is an intriguing chip that connects a USB port to I2C. I2C is a speedy two wire serial interface that a lot of embedded systems already employ, and one that comes built into some microcontrollers. So, using the PDIUSBD11 you could conveniently tie your current I2C-aware product to a PC's USB port.
A number of vendors offer versions of their controllers with an on-board USB port, giving you USB access without using a processor devoted to communications alone. Motorola's products range from a USB-aware 6805 (MC68HC05JB4) to the PowerPC MPC850. AMD added USB to the venerable x86 line with their 186CC. Both Atmel (AT43USB321) and Microchip (PIC 16C745) have microcontroller products with the communications link.
Some vendors offer low level USB drivers you can embedded into your products. Phoenix (http://www.phoenix.com/platform/usbaccess.html), building on their BIOS products, offers firmware-side USB stacks that tie into commercial real time operating systems, such as those from Accelerated Technology, Lynx and Integrated Systems/Wind River..
USB in the Lab
A lot of us use PCs to control short-run products, or to handle simple monitoring tasks in the lab. RS-232 and parallel printer ports, the staple connection for many of these applications, are often just not available on recent PCs. In fact, many laptops now offer these only on an expansion port, yet include USB on the main unit.
A number of companies now sell data acquisition products that incorporate a USB link. For example, National Instruments, the people who provide the very popular LabView software package, sells the "DAQPad" family of instruments (http://www.ni.com), with 16 analog 12 bit inputs, two 12 bit DAC outputs, and a mix of digital I/Os. Iotech's "Personal Daqs" (http://www.iotech.com/catalog/daq/persdaq.html) are very small sensors which offer up to 80 channels of analog and digital inputs, with a 22 bit A/D converter.
If you're building your own low-volume/lab-based link to a PC, and can't stomach the thought of designing your own USB hardware/software, consider the $79 USBSIMM card. This business card-sized controller uses an Anchor Chips 2131 (a USB-aware 8051 derivative). It's a neat and painless way to connect sensors or instruments to USB-based computers.
www.usb.org is the home of the USB organization, a consortium of members who promulgate and enhance the standard. The site has some useful developer information, especially their message forum (www.usb.org/forums/developers/webboard.html) which stays busy with questions and answers from active developers.
Jan Axelson's USB Complete (1999, LakeView Research, ISBN 0-9650819-3-1) is a very readable and comprehensive book that covers all aspects of actually building and coding USB devices. Also see her web site (http://www.lvr.com). Her description of building a HID-class peripheral is the best around.
USB Hardware & Software (1998, Annabooks, ISBN 0-929392-37-X), by a cast of characters who worked on the original USB specification (John Garney, Ed Solari, Shelagh Callahan, Kosar Jaff, and Brad Hosler) bills itself as "the definitive reference to the Universal Serial Bus" - and so it is. A large, dense book, it covers about every nuance of USB communications. This is a "must have" for USB developers.
Wooi Ming Tan's Developing USB PC Peripherals (1997, Annabooks, ISBN 0-929392-64-7) is a slender book that gives a good overview, and which includes some useful sample driver and firmware code on a diskette.
The USB sponsoring organization has wisely created a compliance program to insure that devices meet the standard's specifications. Though no law mandates that any device must pass these tests, doing so insures that the user's experience with your products will be as trouble-free as possible. Products meeting the compliance program's cull get added to the Integrator's List, a sort of imprimatur so customers can be sure that, from a communications perspective at least, the unit works properly.
Nothing stands still in this industry, not even the relatively new USB standard. Version 2.0, which may be formalized as you read this, extends the communications speed to a breathtaking 480 Mbs. Clearly, new classes of applications are not far away.