This is going to be my first post in a long time. Long story short: got married, got fat, got divorced. Back to tinkering with hardware 🙂

I’ve recently been engaged on a project that involves Raspberry Pi and computer vision. The computer vision part is accomplished via a cheap USB cam, using the UVC video driver that ships with most Linux distros. After turning the camera on and off multiple times I noticed that I started getting garbage over the wire. Unplugging the camera and plugging it back in always solved the problem. So I decided to find a way to programmatically power-cycle a specific USB device using a shell script, which I could invoke from my Java code. Here’s what worked for me:

First, you need to allow permissions to power cycle USB devices. I used a VERY CRUDE method, because I’m a noob and decided to abuse chmod:

# Allow USB power cycling via software
sudo chmod 777 /sys/bus/usb/drivers/usb/bind
sudo chmod 777 /sys/bus/usb/drivers/usb/unbind

Once you do this, your application (and ANY application) can now address the RPi’s USB hub. You can shut down individual devices, or the entire hub. Look up how USB device addressing works. If you’re not sure, you can print out what the specific device addresses for the driver you’re using (in my case it’s uvcvideo)

# Print out USB ports to which the camera is connected
echo 'Device locations:'
ls /sys/bus/usb/drivers/uvcvideo/ | grep '1-'

And here’s the golden nugget. This is how you power cycle a specific USB port:


echo 'Device locations:'
ls /sys/bus/usb/drivers/uvcvideo/ | grep '1-'
echo 'Unbinding device'
echo '1-1.2' > /sys/bus/usb/drivers/usb/unbind
sleep 0.5
echo 'Binding device'
echo '1-1.2' > /sys/bus/usb/drivers/usb/bind
echo 'Power cycle complete'

I’ve tested this for months. Works every time. Just be careful which device you power cycle, because the Ethernet adapter happens to be on the same USB hub as everything else that’s plugged in.

Best of luck!