26 January 2009

USB Part 5 – Using the USB Serial library

Now that we’ve explored some of the ins and outs of the PicPack USB library, it’s time to look at a more complex and probably more useful example. Up until now we’ve relied on using serial ports to act as our debug interface. It would be nice if we could use USB for this purpose entirely? This is where the Communication Device Class (CDC) comes in.

The CDC covers many things, including the thing that we’re interested in, a connection to a modem-like device. In fact, we define our “modem” as so dumb it can’t even make calls on a phone line – which sounds pretty much like a serial port to me.

If you want to get cracking, open up the usb_serial project in the demos\usb_serial directory. It’s all set for burning into a 18f4550 on a board like the TechToys USB demo board. If you burn the .hex file, then plug your device into a PC, it will ask for a driver file. Just point the install program at the picpack_cdc.inf file in the tools\usb_cdc_inf directory. For reasons best known to Microsoft, Windows requires this file, even though all it says is “this is a standard USB serial port”. Go figure. Linux doesn’t require any sort of driver information at all.

Using the PicPack CDC routines is pretty easy. You can use them just like you’ve been using the pic_serial routines up til now.

In your system setup routine, put:

// Setup Communication Device Class routines

// Setup USB

// Turn on interrupts

In your interrupt service routine you will need to include:


which handles both reception and transmission.

In your main() routine, kick off USB negotiations using:


You can wait for the negotiations to finish using

while (usb_configured == 0) {

We’ll use the callback that’s triggered when the configuration is complete to set the usb_configured variable:that we were checking in that last loop:

void usb_device_configured_callback() {
usb_configured = 1;

And that’s it. Once the link is up, you can use the usb_cdc_ routines like usb_cdc_putc just like their pic_serial equivalents. In fact, aside from these routines, you can see that the complete program looks remarkably similar to the pic_serial demo itself.

You can #define USB_DEBUG and CDC_DEBUG in the config.h file if you’d like to get more detail on the USB process itself. This is handy if you want to understand how the CDC class code and the PicPack USB stack itself work.

In the next tutorial we’ll delve a bit deeper into the CDC routines. The CDC is a more complex example than our previous USB joy mouse which sent data in only one direction, and didn’t make use of class control transfers and multiple endpoints.

1 comment:

Anonymous said...

any idea when you'll write more tutorials?