Saturday, 27 July 2024

USB HID gadget with Raspberry Pi OS

For some reason the wifi on my PiKVM installation on my Raspberry Pi Zero 2 W described in my previous post has become unstable. Also keeping underlying Arch Linux updated with my ansible update script is a challenge due to PiKVM keeps file system read-only by default. To solve both issues I moved USB HID gadget functionality to Raspberry Pi OS. Started with flashing latest Bookworm 64 bit Lite version to my Raspberry Pi Zero 2 W. I broadly used the configuration in this post.

jordana@pi02w2:~ $ sudo nano /boot/firmware/config.txt
dtoverlay=dwc2,dr_mode=peripheral
jordana@pi02w:~ $ sudo nano /boot/firmware/cmdline.txt
modules-load=dwc2,g_hid rootwait
jordana@pi02w2:~ $ sudo nano /etc/modules
dwc2
libcomposite
jordana@pi02w2:~ $ sudo nano /usr/bin/hid_keyboard_setup.sh
#!/bin/bash
cd /sys/kernel/config/usb_gadget/
mkdir -p g1
cd g1
echo 0x1d6b > idVendor # Linux Foundation
echo 0x0104 > idProduct # Multifunction Composite Gadget
echo 0x0100 > bcdDevice
echo 0x0200 > bcdUSB
mkdir -p strings/0x409
echo "0123456789" > strings/0x409/serialnumber
echo "Raspberry Pi" > strings/0x409/manufacturer
echo "Pi Zero Keyboard" > strings/0x409/product
mkdir -p configs/c.1/strings/0x409
echo "Config 1: HID Keyboard" > configs/c.1/strings/0x409/configuration
echo 120 > configs/c.1/MaxPower
mkdir -p functions/hid.usb0
echo 1 > functions/hid.usb0/protocol
echo 1 > functions/hid.usb0/subclass
echo 8 > functions/hid.usb0/report_length
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\x65\\x05\\x07\\x19\\x00\\x29\\x65\\x81\\x00\\xc0 > functions/hid.usb0/report_desc
ln -s functions/hid.usb0 configs/c.1/
ls /sys/class/udc > UDC
jordana@pi02w2:~ $ sudo chmod +x /usr/bin/hid_keyboard_setup.sh
jordana@pi02w2:~ $ sudo nano /etc/rc.local
/usr/bin/hid_keyboard_setup.sh

I added the script with support for 0-9 numeric keys, arrow keys and mapped Enter and Esc for remotely driving UI on a STB that support USB HID keyboard to my git repository here.

UPDATE

Configuration above have been updated that supports Raspberry Pi 4 also with its OTG capability on its USB-C port. In order to connect Raspberry Pi 4 to a low power USB 2.0 keyboard port I had to provide power via GPIO. Pimoroni has a nice solution for this here

No comments:

Post a Comment