monotux.tech

Resetting an USB port

USB, Hardware, Linux

This is something I need often enough I’ve gotten tired of finding it online. The best thing would probably be to buy better USB peripherals but this is the second best thing in this. :-)

First, some source code:

/* usbreset -- send a USB port reset to a USB device */

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>

#include <linux/usbdevice_fs.h>


int main(int argc, char **argv)
{
    const char *filename;
    int fd;
    int rc;

    if (argc != 2) {
        fprintf(stderr, "Usage: usbreset device-filename\n");
        return 1;
    }
    filename = argv[1];

    fd = open(filename, O_WRONLY);
    if (fd < 0) {
        perror("Error opening output file");
        return 1;
    }

    printf("Resetting USB device %s\n", filename);
    rc = ioctl(fd, USBDEVFS_RESET, 0);
    if (rc < 0) {
        perror("Error in ioctl");
        return 1;
    }
    printf("Reset successful\n");

    close(fd);
    return 0;
}

Save it as usbreset.c and compile it:

cc usbreset.c -o usbreset

Make it executable:

chmod +x usbreset

Then, identify which device that needs a reset:

# lsusb
Bus 002 Device 002: ID 0438:7900 Advanced Micro Devices, Inc. Root Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 0438:7900 Advanced Micro Devices, Inc. Root Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 003: ID 1a86:7523 QinHeng Electronics CH340 serial converter
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

In my case the QinHeng Electronics CH340 serial converter needed a restart. Note the bus and device numbers, apply them like so:

# ./usbreset /dev/bus/usb/003/003
Resetting USB device /dev/bus/usb/003/003
Reset successful

Credits #