- Program your microcontrollers from WSL2 with USB support
- What you need to get started
- Windows 10 or 11
- WSL
- usbipd-win
- Windows Terminal (optional)
- Using USB from WSL
- Attaching a device to WSL from Windows
- Accessing a USB device from WSL
- What to keep in mind
- USB all the things!
- Talk with an Expert
- Подключение USB-устройств
- Предварительные требования
- Установка проекта USBIPD-WIN
- Установка средств USBIP и аппаратной базы данных в Linux
- Подключение USB-устройства
- Connect USB devices
- Prerequisites
- Install the USBIPD-WIN project
- Install the USBIP tools and hardware database in Linux
- Attach a USB device
Program your microcontrollers from WSL2 with USB support
USB is one of the most important computer interfaces for an embedded developer. It’s how we flash, test and debug our hardware. It is supported on the 3 major desktop operating systems allowing developers to use the OS they are most productive in. Yet, despite having “universal” in its name, USB support isn’t the same everywhere. A device programmer may only have a Windows binary, while a compiler may only work in Linux.
When Microsoft released Windows Subsystem for Linux (WSL), Windows developers were excited about the potential of using both Windows and Linux tools from one machine. At launch, it mostly delivered on that promise with one big caveat: no USB support.
Of course there were hacks with copy/pasting and custom network drivers, but none of them worked reliably. But late last year Microsoft announced that they’ve added USB support to WSL! I was certainly keen to try it out and over the past few months I’ve been testing it as part of my Windows development workflow. It’s now in a state where I can recommend for use to other developers, though there are a few gotchas to make note of (we’ll discuss that later.) Today I will walk you through the basic steps of programming an embedded device over USB using WSL.
What you need to get started
Windows 10 or 11
Obviously to do development on Windows…you need a copy of Windows. What’s less obvious is that WSL & USB are both supported by Windows 10. You just need Windows 10 version 2004 or the latest build of Windows 11.
WSL
There are a few ways to install WSL and you may have WSL already installed on your machine. But before we can get to using USB we need to check which Linux kernel is currently installed. It needs to be a kernel version of 5.10.60.1 or later. You can check by running uname -a .
If you installed WSL using the command line (see docs), then you may have a recent-enough kernel via Windows Update. However, I recommend installing Windows Subsystem for Linux Preview from the Microsoft Store. It’ll keep your WSL kernel up to date without having to wait for a service pack.
You also need a Linux distribution and you can use any distribution you like from the Microsoft Store. I prefer to keep things easy and use Ubuntu.
usbipd-win
This is what makes all the magic happen. The instructions are pretty straightforward. It’s mostly a matter of installing the usbipd-win program on the Windows side and a little bit of configuration on the Linux side.
(If you’re curious how this works, make sure to check out the underlying USB/IP protocol. It’s been part of the Linux kernel for years!)
Windows Terminal (optional)
Strictly not needed to work with WSL or USB, Windows Terminal is a much more modern terminal than what comes stock with Windows or PowerShell. It also offers a tabbed interface which is especially useful when needing to switch between Windows and WSL while managing your USB devices.
Using USB from WSL
With the dependencies out of the way, we can start interacting with a USB device.
Attaching a device to WSL from Windows
You’ll need to get comfortable with usbipd as it’s how we’ll enable USB to be used with WSL. The basic steps are:
- Launch Windows Terminal as an Administrator
- Run usbipd wsl list to list all the devices on your machine, noting the BUS-ID for the device you want to use
- Run usbipd wsl attach —busid= to use the device from WSL
- Run usbipd wsl list again to verify that the device is now being used by WSL
Accessing a USB device from WSL
At this point you have a real USB device in Linux. To quickly verify that everything works:
- Open Ubuntu (doesn’t need to be as an Administrator)
- Run lsusb and note the USB device
- Start interacting with the device like you normally would
I followed the Golioth Getting Started Guide for the ESP32 using the Linux instructions and it worked like a treat. But I’ve also tested the mainline Zephyr, Arduino CLI & an STM32 with dfu-util .
What to keep in mind
If you’re new to Linux, you’ll need to get a little familiar with tools like udev and how to find your device paths, but there are a ton of resources online. Some of the devices I tried already had the udev rules defined in my release of OpenOCD but one didn’t. It took me awhile to figure out the ancient incantation to make udev happy. Usually If you’re using an open source tool they provide pretty good documentation for usage on Linux, so check the manual.
One challenge with this approach is that usbipd tries to re-attach a device if it reboots. This can happen when you flash firmware. It doesn’t always recover, especially if the Bus ID changes, so you may need to re-attach the device. It’s a little annoying if you forget, so make sure you keep that admin console open.
Lastly, while many USB, USB/Serial & HID devices are included with the current WSL kernel, some may not be by default. Leave a comment on this issue if you want to request additional drivers.
USB all the things!
I’m grateful that Microsoft has added support for USB in WSL. It’s not only helpful for Golioth developers but anyone else doing embedded development on Windows. I didn’t go into every bit of detail in this post so if you have any questions or run into issues, feel free to reach out to me on Twitter or join our Discord.
https://blog.golioth.io/wp-content/uploads/2022/04/wsl_usb.png 1080 1920 Jonathan Beri https://blog.golioth.io/wp-content/uploads/2022/02/Golioth_-the-straightforward-commercial-IoT-development-platform-built-for-scale-0.svg Jonathan Beri 2022-04-14 07:34:30 2022-07-27 07:45:08 Program your microcontrollers from WSL2 with USB support
Talk with an Expert
Implementing an IoT project takes a team of people, and we want to help out as part of your team. If you want to troubleshoot a current problem or talk through a new project idea, we’re here for you.
Подключение USB-устройств
В этом руководстве описаны шаги, необходимые для подключения USB-устройства к дистрибутиву Linux, работающему на WSL 2, с помощью проекта с открытым исходным кодом USB/IP usbipd-win.
Настройка проекта USB/IP на компьютере с Windows позволит реализовать распространенные сценарии РАЗРАБОТКИ USB, такие как мигание Arduino или доступ к средству чтения смарт-карт.
Предварительные требования
- Запуск Windows 11 (сборка 22000 или более поздняя). (Поддержка Windows 10 возможна, см. примечание ниже).
- Требуется компьютер с процессором x64/x86. (Arm64 в настоящее время не поддерживается с usbipd-win).
- Дистрибутив Linux установлен и установлен на WSL 2.
- Запуск ядра Linux 5.10.60.1 или более поздней версии.
Чтобы проверить версию и номер сборки Windows, нажмите клавиши WINDOWS+R, введите winver и щелкните ОК. Вы можете выполнить обновление до последней версии Windows, выбрав Пуск>Параметры>Центр обновления Windows>Проверить наличие обновлений. Чтобы проверка версию ядра Linux, откройте дистрибутив Linux и введите команду . uname -a Чтобы вручную обновить ядро до последней версии, откройте PowerShell и введите команду wsl —update.
Windows 11 рекомендуется для подключения USB-устройств к дистрибутиву Linux, работающему на WSL 2. Однако Windows 10 можно использовать для подключения USB-устройств, создав собственное ядро WSL 2 с поддержкой USBIP, следуя инструкциям в репозитории проекта USBIPD-WIN.
Установка проекта USBIPD-WIN
Поддержка подключения USB-устройств изначально недоступна в WSL, поэтому вам потребуется установить проект usbipd-win с открытым исходным кодом.
- Перейдите на страницу последнего выпуска проекта usbipd-win.
- Выберите файл .msi, который скачивает установщик. (Вы можете получить предупреждение с просьбой подтвердить, что вы доверяете этому скачиванию.)
- Запустите скачанный файл установщика usbipd-win_x.msi.
Кроме того, можно установить проект usbipd-win с помощью Диспетчер пакетов Windows (winget). Если вы уже установили winget, просто используйте команду : winget install —interactive —exact dorssel.usbipd-win , чтобы установить usbipd-win. Если вы опустите параметр —interactive, winget может немедленно перезагрузить компьютер, если это необходимо для установки драйверов.
- Служба с именем usbipd (отображаемое имя: УЗЕЛ устройства USBIP). Состояние этой службы можно проверка с помощью приложения «Службы» из Windows.
- Программа usbipd командной строки . Расположение этого средства будет добавлено в переменную среды PATH.
- Правило брандмауэра, которое usbipd позволяет всем локальным подсетям подключаться к службе. Это правило брандмауэра можно изменить для точной настройки управления доступом.
Установка средств USBIP и аппаратной базы данных в Linux
После завершения установки проекта USB/IP необходимо установить средства пользовательского пространства и базу данных идентификаторов оборудования USB. Эти инструкции предназначены для Ubuntu— для других дистрибутивов может потребоваться другой пакет клиента usbip.
В Ubuntu выполните следующую команду:
sudo apt install linux-tools-generic hwdata sudo update-alternatives --install /usr/local/bin/usbip usbip /usr/lib/linux-tools/*-generic/usbip 20
На этом этапе служба запущена в Windows для совместного использования USB-устройств, и в WSL устанавливаются необходимые средства для подключения к общим устройствам.
Подключение USB-устройства
Перед подключением USB-устройства убедитесь, что открыта командная строка WSL. Это позволит сохранить упрощенную виртуальную машину WSL 2 активной.
- Выведите список всех USB-устройств, подключенных к Windows, открыв PowerShell в режиме администратора и введя команду:
Connect USB devices
This guide will walk through the steps necessary to connect a USB device to a Linux distribution running on WSL 2 using the USB/IP open-source project, usbipd-win.
Setting up the USB/IP project on your Windows machine will enable common developer USB scenarios like flashing an Arduino or accessing a smartcard reader.
Prerequisites
- Running Windows 11 (Build 22000 or later). (Windows 10 support is possible, see note below).
- A machine with an x64/x86 processor is required. (Arm64 is currently not supported with usbipd-win).
- Linux distribution installed and set to WSL 2.
- Running Linux kernel 5.10.60.1 or later.
To check your Windows version and build number, select Windows logo key + R, type winver, select OK. You can update to the latest Windows version by selecting Start > Settings > Windows Update > Check for updates. To check your Linux kernel version, open your Linux distribution and enter the command: uname -a . To manually update to the latest kernel, open PowerShell and enter the command: ‘wsl —update`.
Windows 11 is recommended for connecting USB devices to a Linux distribution running on WSL 2. However, Windows 10 can be used to connect USB devices by building your own USBIP enabled WSL 2 kernel following the instructions in the USBIPD-WIN project repo.
Install the USBIPD-WIN project
Support for connecting USB devices is not natively available in WSL, so you will need to install the open-source usbipd-win project.
- Go to the latest release page for the usbipd-win project.
- Select the .msi file, which will download the installer. (You may get a warning asking you to confirm that you trust this download).
- Run the downloaded usbipd-win_x.msi installer file.
Alternatively, you can also install the usbipd-win project using Windows Package Manager (winget). If you have already installed winget, just use the command: winget install —interactive —exact dorssel.usbipd-win to install usbipd-win. If you leave out —interactive, winget may immediately restart your computer if that is required to install the drivers.
- A service called usbipd (display name: USBIP Device Host). You can check the status of this service using the Services app from Windows.
- A command line tool usbipd . The location of this tool will be added to the PATH environment variable.
- A firewall rule called usbipd to allow all local subnets to connect to the service. You can modify this firewall rule to fine tune access control.
Install the USBIP tools and hardware database in Linux
Once the USB/IP project has completed installing, you will need to install the user space tools and a database of USB hardware identifiers. These instructions are for Ubuntu — other distributions may require a different usbip client package.
On Ubuntu, run this command:
sudo apt install linux-tools-generic hwdata sudo update-alternatives --install /usr/local/bin/usbip usbip /usr/lib/linux-tools/*-generic/usbip 20
At this point a service is running on Windows to share USB devices, and the necessary tools are installed in WSL to attach to shared devices.
Attach a USB device
Before attaching your USB device, ensure that a WSL command line is open. This will keep the WSL 2 lightweight VM active.
- List all of the USB devices connected to Windows by opening PowerShell in administrator mode and entering the command:
To learn more about how this works, see the Windows Command Line Blog and the usbipd-win repo on GitHub.