Home Ask Login Register

Developers Planet

Your answer is one click away!

user3528438 February 2016

How to detect when a usb cable is connected/disconnected on the device side in Linux 2.6.37?

I have a embedded device that runs linux 2.6.37.

I want my application to know when the USB is connected.

Currently I can achieve this by pooling /sys/devices/platform/musb/musb-hdrc.0/vbus.

However this approach does not distinguish between a USB charger or a USB host.

I found this udev approach but I don't think it's available in my version of the kernel. because I did not find any USB related nodes in my /dev. This discussing also shows that it might not be feasible, ether.

I also found linux hotplug and tried the netlink example, but I didn't see any output running the example when I connect/disconnect the USB cable.

What I want to do is to detect connection type on the device, when USB is connected, and prepare (unmount file system) and switch to g_file_storage if device is connected to a host, and do nothing if device is connect to a charger.

How shall I achieve this?


Luis Colorado February 2016

To achieve that, you can use the inotify(7) feature, available in all linux kernels to be awaken as soon as some device node gets created in /sys.

To know what type of device you have, you have to read the usb info from proper usb ioctl call (or if you are not a kernel interface expert, using the libusb interface) to get the device vendor, device id and device class fields coming from the device. Normally, the hotplug software gets informed on these clase of events (via a special socket). The most probably reason you don't get the device properly initialized is some misconfiguration in the config files for udev system, which normally has one entry for each possible device vendor/device id pair and allows it to load the appropiate device driver to control it. The process continues with the device driver module creating dynamically the actual devices, and they'll appear in the /dev/ filesystem as a consequence of some other kernel event to udevd.

Read apropiate documents in <linux_src>/Documentation (this directory directory belongs to the linux kernel source code, so you'll probably need to install it), and udevd(8) man pages to be able to add a new usb.

user3528438 February 2016

On 2.6.37 kernel, this could be done by polling


If handshake with host is successful then it will read as "peripheral", if fail it'll be "idle".

Post Status

Asked in February 2016
Viewed 3,894 times
Voted 14
Answered 2 times


Leave an answer

Quote of the day: live life