Files
rover-pi/Scripts/gadget.sh
T
2026-07-02 10:29:54 +00:00

72 lines
2.5 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
# Adapted from
# "Using OTG mode on Raspberry Pi SBCs"
# https://pip-assets.raspberrypi.com/categories/685-app-notes-guides-whitepapers/documents/RP-009276-WP/Using-OTG-mode-on-Raspberry-Pi-SBCs
# Is the dwc2 overlay installed? Nothing will work if it isn't.
if lsmod | grep -q "dwc2"; then
systemd-cat -t gadget.sh -p info echo "DWC2 module loaded, setting up OTG gadget serial and ethernet"
else
systemd-cat -t gadget.sh -p warning echo "DWC2 module missing. Aborting OTG setup."
exit 1
fi
sudo modprobe libcomposite
cd /sys/kernel/config/usb_gadget
# Was the script already run?
if [ -d "MyGadget" ]; then
systemd-cat -t gadget.sh -p warning echo "MyGadget already exists. Aborting OTG setup."
exit 1
fi
# Create our new gadget
sudo mkdir MyGadget
cd MyGadget
# Add some boilerplate data that the gadget needs
echo 0x1d6b > idVendor # Linux Foundations USB VID. Replace with your own VID if required
echo 0x0104 > idProduct # Multifunction Composite Gadget
echo 0x0100 > bcdDevice # v1.0.0
echo 0x0200 > bcdUSB # USB2
mkdir strings/0x409 # 0x409 = English
# Insert your own manufacturer and gadget name here
echo "RaspberryPi" > strings/0x409/manufacturer
echo "MyPiGadget" > strings/0x409/product
# Make the serial number the same as the Raspberry Pi serial number; you can use whatever is required here
SERIAL=`cat /proc/cpuinfo | awk '/Serial/ {print $3}' `
echo $SERIAL > strings/0x409/serialnumber
# Create a configuration area and populate
mkdir configs/c.1
echo 120 > configs/c.1/MaxPower
mkdir configs/c.1/strings/0x409
echo "Config 1" > configs/c.1/strings/0x409/configuration
# Create our specific gadget type
## Mass storage device
### Remember to create the storage block device first
## cd /root
### Example: Make a 256 MB file to act as "USB stick"
## sudo dd if=/dev/zero of=drive.bin bs=1M count=256
### Create a VFAT file system on the backing store
## sudo mkfs.vfat drive.bin
##
# mkdir functions/mass_storage.usb0
## Set up our backing store
# echo "/home/pi/drive.bin" > functions/mass_storage.usb0/lun.0/file
## Link our function to our configuration
#ln -s functions/mass_storage.0 configs/c.1/
## Serial (CDC ACM)
mkdir functions/acm.usb0
ln -s functions/acm.usb0 configs/c.1/
## Ethernet (RNDIS and ECM)
## Of note, this may cause the IP to show up as 127.0.0.1
## and wireless to suddenly fail to connect
mkdir functions/ecm.usb0
ln -s functions/ecm.usb0 configs/c.1/
## USB Device Controller update
UDC=`ls /sys/class/udc`
echo $UDC > UDC