Writing a Simple USB Driver
Since this column began, it has discussed how a Linux driver writer can create various types of kernel drivers, by explaining the different kernel driver interfaces including TTY, serial, I2C and the driver core. It is time to move on now and focus on writing real drivers for real hardware. We start by explaining how to determine what kind of kernel driver interface to use, tricks to help figure out how the hardware actually works and a lot of other real-world knowledge.
Let's begin with a goal of making a simple USB lamp device work well with Linux. Editor Don Marti pointed out a neat device, the USB Visual Signal Indicator, manufactured by Delcom Engineering and shown in Figure 1. I have no relationship with this company; I just think they make nice products. This device can be ordered on-line from the Delcom Web site, www.delcom-eng.com. Don challenged me to get the device working on Linux, and this article explains how I did it.
The first goal in trying to write a driver for a device is to determine how to control the device. Delcom Engineering is nice enough to ship the entire USB protocol specification their devices use with the product, and it also is available on-line for free. This documentation shows what commands the USB controller chip accepts and how to use them. They also provide a Microsoft Windows DLL to help users of other operating systems write code to control the device.
The documentation for this device is only the documentation for the USB controller in the lamp. It does not explicitly say how to turn on the different color LEDs. For this, we have to do a bit of research.
No Docs? Reverse Engineer It!
If the USB protocol for this device had not been documented or available to me, I would have had to reverse engineer this information from the device itself. A handy tool for this kind of work is a free program called USB Snoopy, www.wingmanteam.com/usbsnoopy; another version of it is SnoopyPro, usbsnoop.sourceforge.net. These programs are both Windows programs that allow users to capture the USB data that is sent to and received from any USB device on a Windows system. All a developer needs to do is find a Windows machine, install the Windows driver provided by the manufacturer for the device and run the snoop program. The data is captured to a file to be analyzed later. Perl scripts can help filter some of the extra noise in the output of these snoop programs into an easier format to understand.
Another method a few people have used to reverse engineer the USB protocol of a device is to run a Windows instance using VMware on top of Linux. VMware enables the Windows instance to talk to all of the USB devices plugged in to the Linux machine by sending data to Linux though the usbfs. A simple modification to the usbfs causes all data flowing though it to be logged to the kernel log. Using this, the full USB traffic stream can be captured and later analyzed.
After opening up the lamp device, making sure not to lose the spring that easily pops out when unscrewing the device, the circuit board can be inspected (Figure 2). Using an ohmmeter, or any kind of device for detecting a closed circuit, it was determined that the three different LEDs are connected to the first three pins of port 1 on the main controller chip.
In reading the documentation, the USB command to control the levels of the port 1 pins is Major 10, Minor 2, Length 0. The command writes the least significant byte of the USB command packet to port 1, and port 1 is defaulted high after reset. So, that is the USB command we need to send to the device to change the different LEDs.
Now that we know the command to enable a port pin, we need to determine which LED color is connected to which pin. This is easy to do with a simple program that runs through all possible combinations of different values for the three port pins and then sends the value to the device. This program enabled me to create a table of values and LED colors (Table 1).
Table 1. Port Values and the Resulting LED Patterns
| Port value in hex | Port value in binary | LEDs on |
|---|---|---|
| 0x00 | 000 | Red, Green, Blue |
| 0x01 | 001 | Red, Blue |
| 0x02 | 010 | Green, Blue |
| 0x03 | 011 | Blue |
| 0x04 | 100 | Red, Green |
| 0x05 | 101 | Red |
| 0x06 | 110 | Green |
| 0x07 | 111 | No LEDs on |
So, if all pins on the port are enabled (a value of 0x07 hex), no LEDs are on. This matches up with the note in the data sheet that stated, “Port 1 is defaulted high after reset.” It would make sense not to have any LEDs enabled when the device is first plugged in. This means we need to turn port pins low (off) in order to turn on the LED for that pin. Using the table, we can determine that the blue LED is controlled by pin 2, the red LED by pin 1 and the green LED by pin 0.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- Designing Electronics with Linux
- New Products
- Linux Systems Administrator
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Dynamic DNS—an Object Lesson in Problem Solving
- Web & UI Developer (JavaScript & j Query)
- Using Salt Stack and Vagrant for Drupal Development
- Reply to comment | Linux Journal
5 hours 39 min ago - Dynamic DNS
6 hours 13 min ago - Reply to comment | Linux Journal
7 hours 12 min ago - Reply to comment | Linux Journal
8 hours 2 min ago - Not free anymore
12 hours 4 min ago - Great
15 hours 51 min ago - Reply to comment | Linux Journal
15 hours 59 min ago - Understanding the Linux Kernel
18 hours 13 min ago - General
20 hours 43 min ago - Kernel Problem
1 day 6 hours ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?






Comments
How To Get Port Values and the Resulting LED Patterns ???
Hi
Thanks For this guide but I want to know how to get Port Values and the Resulting LED Patterns without documents of the device ???
Souce
I was actually trying to write a kernel driver for usb and was hooked up reading this article only to find out it's been around for 6 years! Even so I've learned alot from this article. This is a great tutorial to make usb drivers, however I'm quite stucked on the process of compiling the source.
Delphi Hid get path
The first time I use SetupDiGetDeviceInterfaceDetailA
It returns GetLastError = ERROR_INSUFFICIENT_BUFFER or 78
and a byesreturned is a good expected number
DevData ( is the record below)
TSPDevInfoData = packed record
Size: DWORD;
ClassGuid: TGUID;
DevInst: DWORD;
Reserved: DWord;
end;
with TSPDevInfoData.ClassGuid = the Registry USB controller GUID
When I call SetupDiGetDeviceInterfaceDetailA a second time it hates me
real bad. I'm not sure how to convert BytesReturned into my DevData.size or
TSPDeviceInterfaceDetailDataA.size correctly.
I have checked my Structures through and through
The new structure being:-
TSPDeviceInterfaceDetailDataA = record
Size: DWord;
DevicePath: Array [0..255] of AnsiChar;
end;
//*********************************************************
LastSuccess := SetupDiGetDeviceInterfaceDetailA(IsDevPtr, DevData, nil, 0, @BytesReturned, nil);
if (BytesReturned <> 0) and (GetLastError = ERROR_INSUFFICIENT_BUFFER{ 122 }) then
begin
ADWord := BytesReturned + Sizeof(TSPDeviceInterfaceDetailDataA) + 6; // Sizeof(TSPDeviceInterfaceDetailDataA)is one size in delphi
Str.Size := ADWord; // this is a memory block
DevIntfcDetailDataA := Str.Memory;
//this makes a structure be in the memory block
LastSuccess := SetupDiGetDeviceInterfaceDetailA(IsDevPtr,
DevData,
DevIntfcDetailDataA,
BytesReturned,
@ADWord,
nil);
// lastsuccess is always and error
can you suggest anything I have forgotten
lexdeanair at Hotmail.com
writing protcol cool disk
Hello
i want save data(with txt format) on cool disk by microcontroller AVR.
For this i use cinvertor USRT to USB.
my question is : what is protcol cool disk for writing data on it?
HELLO
hello plz i need help urgently !
i atached my motorola netmon phone to my USB , and it didnt present in the dev/ttyUSB1 directory ...
second think , in c++ how do i write a fucntion that send command to the usb modem ( watever it is )
thx a lot plz help !
USB Lamp writer error!
Hello Greg,
Nice article, I bought the lamp
and I tried it out on Windows and Linux.
I get the following error:
bash: echo: writer error: Success
My system is Ubuntu Jaunty Jackrabbit (9.04)
kernel 2.6.28-15
I've got my usb files in the following directory:
/sys/bus/usb/drivers/usbled/2-2:1.0
|-- bAlternateSetting
|-- bInterfaceClass
|-- bInterfaceNumber
|-- bInterfaceProtocol
|-- bInterfaceSubClass
|-- bNumEndpoints
|-- blue
|-- driver -> ../../../../../../bus/usb/drivers/usbled
|-- green
|-- modalias
|-- power
| `-- wakeup
|-- red
|-- subsystem -> ../../../../../../bus/usb
|-- supports_autosuspend
`-- uevent
Scratching my head... any ideas appreciated...
Thanks
USB lamp enquiry
Hello Ajay Abraham,
This is Nagesh A from India.
I have gone through this artical, and found interested.
As I have seen your comment on this, I would like to ask you, how can I buy this product, thinking you might be aware of buying this product.
Please give some detail, if you know.
thank you,
-Nagesh A
USB Lamp writer error
The command I gave was : echo 1 > blue
Solved
System : slax
kernel :2.6.27.27
Hardware : Lenovo Thinkpad R60
echo 1 > blue
echo 1 > red
echo 1 >green
I didnt even have to write the driver
I just used usbfs mounted on sys/bus/usb/devices
Simply amazing
Awsome tutorial . very very inspiring .Great job ,I helped me put courage into me to write a device driver..
A driver suggestion
How about a driver for the Wireless PC Lock
http://www.gadgets.co.uk/item/USBLOCK/USB-Wireless-PC-Lock.html
The bundled software for windows is godawful and I think someone already did a tutorial on writing new software for the device to enable locking of the system etc. Would be nice if I could get this device working under Linux so I could look into writing some software to secure the system when I step away!
~T
Some question
Hi! Is the way to read messages from usb mouse? I went to /dev/ folder. What I should to do? I only need to send/receive data via usb interface.
Re
I never thought that device driver writing could be this straightforward. Wow! Superb tutorial and very very inspiring. I simply love it.
Problem when compilling
Hi !
Thank you for this tutorial which allow easly to develop my own driver.
However, I have a problem when I'm compiling your file. Normally I have all the libraries (libusb, libusb-dev). I just replace config.h by autoconf.h because ubuntu use this file rather than config.h
My error is:
driverUSB_HID.c:154: error: unknown field ‘owner’ specified in initializer
So could you please help me ?
BR
Eloi
Mr Greg , I m
Mr Greg ,
I m writing a driver for usb device in linux 2.4 version ,how i can get get minor no dynamically from usb core , how to create node in the /dev with using major and minor no without devfs .
Thank you
with regards
Bhanu
ThinkGeek USB Rocket Launcher
You should do a Linux device driver for the USB Rocket Launcher:
http://www.thinkgeek.com/geektoys/warfare/8a0f/
USB dirver
Hey was wondering which would be the best method for writing a USB game control driver e.g. Would you make the driver listen for when a button is pressed or would you write the driver and then a program in say C to retrieve the current state of the button?
im wrting a driver programm..Help me...
Im writing a driver program for transfering data's between PC and my SWITCH(Its an telcom equipment)in Linux platform.Getting cofused in "how to program for send and receive data's b/w PC and my switch.Please help me to get clear idea about that.
USB driver for MPEG 4
Hi I want to write a driver for USB streaming of MPEG 4 Video. I am not sure how and where to start. I have MPEG 4 video capture and the video is saved as a file onto the system. How should I start writing the driver for streaming the video instead of saving it in the system?
Doing it
Their are a few ways to do this. The hardest way,would be to write a "pure driver". To do that, you would have to first know how to the USB HID's Subclass and the exact paramters on using it. Also, if you told it to save the data to the device, and then later retrive it, it would deffinitly reduc bottlenecks. There is lots more and the hardest part would have to do with the audio. The easiest way to do it,is with Java. Get the Windows Media SDK, use Java to interface with the device. If you look at some documentation for the WMSDK, it should tell you all the video paramters and how to set it up. There should be a HID protocol for streaming data between devices maybe MTP, I am not fully sure on the semantics,but that should help you.
USB cable to work as a communication medium
How can I write a driver for a simple two headed USB cable that enables it to work as a communication medium? The only thing I want it to do is to be able to send and receive data from one machine to/from another, and they're connected to each other using this USB cable. /*the cable is a wire, with two USB plugs on both ends*/I appreciate any pointer to a reference or help.
error when i passs command line argument
hi,
when i pass this argument then this error appear.
plz help me.
[root@localhost 4-1:1.0]# echo '1' > blue
bash: echo: write error: Success
thnx
Write Error
I get the same write error. Did you find a resolution?
try passing it without the
try passing it without the '' like echo 1 > blue
Help needed
Hi Greg,
I saw your posts, its very nice and i got a lot of knowledge from them. Can you do me a favour? I'm writing a host side USB driver for ucos. Can you help me how to start....
It should be like it should check for the vendor id and for product id then it should load the driver. It should also have routines for endpoint creations. If you have any idea on this just mail to the below address
hssiddhu@yahoo.com
Thanks in advance
Siddhu
i'm writing a kernel driver for usb on arm linux-2.6.20
Hai
I'm pavan. I'm writing the kernel driver for usb.All the code is available on the kernel and i enabled the relavent features in the menuconfig .when i insert the following modules ,usbcore.ko,hid.ko,usbhid.ko,usb-stotage.ko and ohci-hcd.ko.Its giving the messages that
insmod usbcore.ko
usbcore: registered new interface driver usbfs
usbcore: registered new interface driver hub
usbcore: registered new device driver usb
insmod usbhid.ko
usbcore: registered new interface driver usbhid
drivers/usb/input/hid-core.c: v2.6:USB HID core driver
insmod usb-storage.ko
Initializing USB Mass Storage driver...
usbcore: registered new interface driver usb-storage
USB Mass Storage support registered.
insmod ohci-hcd.ko
probe in platform.c is working<7>In ohci_hcd_pxa27x_drv_probe
in last module i.e ohci-hcd.ko ,its terminating by -ENODEV this i got by printk. i hope the usb is not detecting the devices ,inorder to detect devices what changes i have to made in the kenel.
i'm struck from 3days to debug this problem ,please if anyone have idea about this please share with me.
with regards
pavan
usbreplay
http://linuxtv.org/v4lwiki/index.php/USBVideo
please have a look at usbreplay and co. these tools might ease up everything quite alot
Now Delcom has variable intensity LED lights?
Looks like their latest products allow setting brightness per color?
Also looks like they cost around eighty bucks?!?
Re: Writing a Simple USB Driver
Hi there,
I am planing to write a virtual device which use USB port to talk with the computer. So, my idea is I want to developt a virtual device connect with the PC through USB port. I mean, if you have an usb lamp and you begin write a drive for it. You have a specification of the lamp. And you plug the lamp to the pc. In my case, i want to build my lamp by the software with all properties like a real lamp. So, my first problem is i don't know how to write a virtual device run on both Linux and Windows. So any idea help me now.
Thanks a lot.
Phong
Re: Writing a Simple USB Driver
Greg:
Excellent article. I went with the Delcom "USB Numeric Display", which is a numeric counter.
I noticed something on my system. When I create device files under the /sys/bus/usb/drivers/mydevice directory, and send data to it with the echo command, I can hear the disk access on my computer... It's really getting hit with a lot of data; Perl script that writes lots of changing data to the USB device. Is this normal? I'm making changes in my program so that data goes to the device from a "/proc/mydevice/entries" instead, since "/proc" seems to be mounted in ram vs. /sys on the hard drive.
I'm running 2.6.4 and /sys was mounted with "sysfs /sys sysfs defaults 0 0" in my /etc/fstab. Here's a link to how I setup 2.6
http://osdn.dl.sourceforge.net/sourceforge/souptonuts/README_26.txt
Its seems problematic if new directory trees created under /sys/bus... for input will require disk reads and writes. Maybe I'm overlooking something?
Regards,
Mike Chirico
Re: Writing a Simple USB Driver
I stand corrected.... I had the debug commands "dev_dbg" writing to the log files. Ok, good. I'm on my way.
Regards,
Mike Chirico
Re: Writing a Simple USB Driver
Here's the code if interested
code
Regards,
Mike Chirico
Re: Writing a Simple USB Driver
Great article. I'd like see an article on creating your own USB device and then creating a kernel driver for it.
Re: Writing a Simple USB Driver
Very good article, in this case, you writing a simple driver for a Led lamp. But I am researching now a virtual program simulate a led lamp and I am not found any document for this.
Re: Writing a Simple USB Driver
Looks very cool -- thanks for the article, Greg. I've ordered one of these already to set up a weather-forcast indicator to be installed by my front door.
It looks from the documentation that the device has a programmable flash rate -- it'd be cool to see support for that in the driver. And maybe the buzzer, although I don't think I have a use for that.