ResearchGate-logo

ResearchGate Raspberry Pi Single Board Computer

ResearchGate-Raspberry-Pi-Single-Board-Computer-product

Информация за продукта

Спецификации

  • Manufacturer: Raspberry Pi Ltd
  • Дата на изграждане: 01 г.
  • Build Version: 99a8b0292e31
  • Supported Raspberry Pi Products: Pi Zero, Pi Zero 2 W, Pi 1 AB, Pi 2, Pi 3, Pi 4, Pi 5, Compute Modules CM1, CM3, CM4, CM5

Колофон
© 2022-2025 Raspberry Pi Ltd

This documentation is licensed under a Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND).

Освобождаване 1
Дата на изграждане 01/10/2025
Версия за изграждане 99a8b0292e31

Правна бележка за отказ от отговорност
TECHNICAL AND RELIABILITY DATA FOR RASPBERRY PI PRODUCTS (INCLUDING DATASHEETS) AS MODIFIED FROM TIME TO TIME (“RESOURCES”) ARE PROVIDED BY RASPBERRY PI LTD (“RPL”) “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN NO EVENT SHALL RPL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE RESOURCES, EVEN IF ADVISED OF THE POSSI-BILITY OF SUCH DAMAGE.

RPL си запазва правото да прави подобрения, подобрения, корекции или каквито и да е други модификации на РЕСУРСИТЕ или продуктите, описани в тях, по всяко време и без допълнително известие.
РЕСУРСИТЕ са предназначени за опитни потребители с подходящи нива на познания в областта на дизайна. Потребителите са изцяло отговорни за техния избор и използване на РЕСУРСИТЕ и всяко приложение на продуктите, описани в тях. Потребителят се съгласява да обезщети и предпази RPL от всички задължения, разходи, щети или други загуби, произтичащи от тяхното използване на РЕСУРСИ.
RPL предоставя на потребителите разрешение да използват РЕСУРСИ единствено във връзка с продуктите Raspberry Pi. Всяка друга употреба на РЕСУРСИ е забранена. Не се предоставя лиценз за други права на интелектуална собственост или права на трета страна.

ВИСОКОРИСКОВИ ДЕЙНОСТИ. Продуктите Raspberry Pi не са проектирани, произведени или предназначени за използване в опасни среди, изискващи безопасна работа, като например при експлоатацията на ядрени съоръжения, навигационни или комуникационни системи на самолети, контрол на въздушното движение, оръжейни системи или критични за безопасността приложения (включително поддържащи живота системи и други медицински устройства), при които повредата на продуктите може да доведе директно до смърт, лично нараняване или тежки физически или екологични щети („Дейности с висок риск“). RPL изрично отхвърля всякакви изрични или подразбиращи се гаранции за годност за дейности с висок риск и не поема отговорност за използване или включване на продукти на Raspberry Pi в дейности с висок риск.
Продуктите Raspberry Pi се предоставят в съответствие със Стандартните условия на RPL. Предоставянето на РЕСУРСИ от RPL не разширява или по друг начин променя Стандартните условия на RPL, включително, но не само, отказите от отговорност и гаранциите, изразени в тях.

История на версиите на документа

Освобождаване Дата Описание
1 1 октомври 2025 г Първоначално издание

Обхват на документа
Този документ се отнася за следните продукти на Raspberry Pi:

Single Board Computers / SBCs

Пи нула Pi Zero 2 Пи 1 Пи 2 Пи 3 Пи 4 Пи 5

Compute Modules

CM1 CM3 CM4 CM5

Въведение

USB On-The-Go (OTG) is a specification that allows a device to function either as a USB host (like a PC) or as a USB device/peripheral (like a keyboard, an Ethernet adapter, or a mass storage device). The ‘USB On-The-Go’ Wikipedia page provides a lot of detail on the OTG specification: https://en.wikipedia.org/wiki/USB_On-The-Go.
Usually, a USB connection involves a fixed host (e.g. a computer) and a peripheral (e.g. a mouse). USB OTG allows a device to switch between the two. For example, a Raspberry Pi could act as a host when reading files from a flash drive, or function as a flash drive itself when connected to a computer.

The Raspberry Pi family includes several boards that can function in OTG/peripheral mode, but support differs depending on the model and the system on chip (SoC). When acting in this peripheral mode, the device is often referred to as a ‘gadget’.
This whitepaper walks through the Raspberry Pi SBC lineup, explains their OTG capabilities, and provides configuration/code examples. It covers two distinct OTG mechanisms: the legacy method, which is still very popular and is described first, followed by the currently recommended scheme, ConfigFS .

Legacy OTG

Raspberry Pi Zero / Zero W / Zero 2 W
These boards are the most OTG-friendly in the Raspberry Pi family. They expose the SoC’s USB controller directly on the USB data port (the one labelled USB, not PWR IN), and the onboard software can be configured to make your Raspberry Pi act as an OTG device.

Enabling OTG Mode

Съвет: Because you are using the only USB port on Raspberry Pi Zero for OTG purposes, you will not be able to plug in a keyboard or a mouse. You can instead use a Wi-Fi connection and SSH to communicate with Raspberry Pi Zero…

dtoverlay=dwc2

Now we need to configure the software to connect the requested OTG driver to the USB system…

console=serial0,115200 console=tty1 root=PARTUUID=xxxxxxxx-02 rootfstype=ext4 fsck.repair=yes rootwait modules-load=dwc2,g_ether

Other Gadget Modules
Вместо да g_ether, you can try:

  • g_serial: Appears as a USB serial device
  • g_mass_storage: Exposes an image file as a flash drive
  • g_composite: Emulates a composite device

съвет
A USB composite device is a single physical device that functions as multiple independent devices to a computer, appearing as several separate interfaces or device classes. It combines different functionalities, such as a keyboard and a mouse, or a storage drive and a webcam, into a single USB device and connector. When connected, the operating system recognises and uses separate drivers for each of the device’s distinct functions, allowing them to operate independently.

To create a USB serial gadget, we can load the appropriate module from the command line:

  • Код
  • sudo modprobe g_serial

When connected to a Windows PC, the Raspberry Pi will appear as a COM port in the Device Manager; when connected to a Linux device (e.g. a Raspberry Pi SBC), it will appear as a serial device like /dev/ttyACM0 .

Raspberry Pi 4 and 5 (OTG on the USB-C power port)
Raspberry Pi 4′s USB-C power/OTG port supports peripheral mode when it is not being used to power the board.
Raspberry Pi 5 introduces a PCIe-attached USB controller, which does not support OTG. However, as with Raspberry Pi 4, the native OTG peripheral function on the SoC is exposed through the power connector.

стъпки
Power your Raspberry Pi through the GPIO header (5V and GND), leaving the USB-C free.
Connect the USB-C port to your host computer.

Enable OTG in /boot/firmware/config.txt 

Код
dtoverlay=dwc2,dr_mode=peripheral

Забележка
You need the dr_mode=peripheral option on the overlay to force the controller into OTG peripheral (rather than host) mode, as the OTG_ID line that would normally do the selection is not present on Raspberry Pi 4 or 5.)

Load a gadget module (Ethernet):
Код
sudo modprobe g_ether
Your Raspberry Pi will now enumerate as a USB device to the host.

съвет
Not all host systems handle Raspberry Pi 4′s OTG mode reliably. Ethernet and serial work best.

Raspberry Pi Compute Module series
Raspberry Pi Compute Module 1, 3, 3+ and 4 expose the SoC’s USB OTG controller directly to the carrier board, making them highly flexible.
CM1/CM3/CM3+ The USB OTG interface is available on dedicated pins; carrier boards often expose this via a micro-USB port. CM4 Offers an OTG-capable USB 2.0 interface (USB_OTG). This is routed to the Compute Module 4 IO Board’s micro-USB connector.

CM4 OTG example (Ethernet gadget)
Plug a micro-USB cable into the USB port on the IO Board.

In /boot/firmware/config.txt , add:

Код
dtoverlay=dwc2,dr_mode=peripheral

In /boot/cmdline.txt, add:

  • Код
  • modules-load=dwc2,g_ether

Reboot. Compute Module 4 will now appear as a USB Ethernet adapter.

Raspberry Pi A, B, B+, 2B, 3B, 3B+
The USB ports on these models are connected through a hub chip (LAN9512/LAN9514 or VIA Labs), which strips away OTG capabilities. They can only operate as USB hosts, so no OTG support is available.

Using the various device types
This section describes how to set up the most common gadget modes.

Устройства за масово съхранение
In order to use a Raspberry Pi as a mass storage device (like a USB stick), you will need to create a backing file to hold the stored data:

  • Код
    • # Прample: 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
  • Edit /etc/modprobe.d/g_mass_storage.conf to tell the system to use the backing store:
    • Код
    • options g_mass_storage file=/drive.bin stall=0 removable=1
    • You can examine the contents of the backing store by mounting it on your Raspberry Pi. Here we mount it in a folder called mountpoint :
  • Код
    • sudo mkdir mountpoint
    • sudo mount -o loop drive.bin mountpoint

You’ll need to adjust the paths as appropriate.

Ethernet devices
When the g_ether device is plugged into a Linux host, it will usually appear as a network interface named usb0 (when using ifconfig ).
You can (usually) connect to the device using SSH, as follows:

  • Код
  • ssh pi@raspberrypi.local

Серийни устройства

When a Raspberry Pi is set up as a g_serial device, a new serial device will appear (when using Raspberry Pi OS Bookworm with a 6.12.34 kernel, this was /dev/ttyGS0 ). When that Raspberry Pi device is then plugged into a (for example, Linux) host, the device will be recognised as a CDC ACM–compliant device and will appear as another serial port. For example, on a Raspberry Pi 500 running Bookworm, it appears as /dev/ttyACM0 .
Under Linux, you can test the serial link by using screen on each device. If using Windows on the host, something like Putty should work well.

On your Raspberry Pi:

  • Код
  • screen /dev/ttyGS0

On a Linux host:

  • Код
  • екран /dev/ttyACM0

Then type something into each window — the output should appear on the other screen instead.

Забележка
If screen is not installed, use sudo apt install screen in a terminal window.
It’s easy to see how this functionality could be used to provide a serial interface to a Raspberry Pi device that monitors a number of sensors (e.g. via I2C or SPI) and passes the collated information back, via the serial port, to the host computer.

ConfigFS/usb_gadget: a brave new world

Although they are by far the most common way to set up OTG on Raspberry Pi devices, the mechanisms described above have actually been superseded by something called usb_gadget , which is part of ConfigFS.
ConfigFS is a Linux kernel interface (a virtual file system mounted at /sys/kernel/config ) used to configure kernel objects —including USB gadget drivers — in a modular way. Using ConfigFS / usb_gadget is more flexible than the old g_mass_storage /g_ether method, because you can compose multiple USB functions (e.g. Ethernet + serial + mass storage) at once.
However, this extra functionality does come with a higher setup cost.
The basic idea is that a set of virtual folders and files is created under the /sys/kernel/config folder, which defines the gadget required.
Some kernel documentation on usb_gadgets is available here: https://docs.kernel.org/driver-api/usb/gadget.html и https://www.kernel.org/doc/Documentation/ABI/testing/configfs-usb-gadget.

Настройка
Setting up the DWC USB peripheral is the same as in legacy mode. Edit config.txt as sudo and add:

ResearchGate-Raspberry-Pi-Single-Board-Computer- (1)

We can check that it has loaded properly by looking at the contents of /sys/kernel/config , which should now contain a folder called usb_gadget .
The creation of the actual USB gadget is next, which involves making a folder with the name of the gadget and then creating a set of entries within that folder to define the gadget’s properties. This bash script excerpt does most of the required setup:

ResearchGate-Raspberry-Pi-Single-Board-Computer- (2) ResearchGate-Raspberry-Pi-Single-Board-Computer- (3)

Now that the basic device data has been set up, we need to tell the device exactly what it is. Creating each device is as simple as creating a folder in the ConfigFS gadget’s functions folder and then linking that folder to the configuration entry within the same gadget.

Serial (CDC ACM):

ResearchGate-Raspberry-Pi-Single-Board-Computer- (4)

Ethernet (RNDIS and ECM):

ResearchGate-Raspberry-Pi-Single-Board-Computer- (5) Масово съхранение:
As with the legacy setup, we need a backing store for our mass storage gadget:

ResearchGate-Raspberry-Pi-Single-Board-Computer- (6)

And to use that:

ResearchGate-Raspberry-Pi-Single-Board-Computer- (7)

съвет
/sys/class/udc is a directory within the sysfs file system that represents the available USB device controllers (UDCs). It allows the kernel’s USB gadget subsystem to identify and interact with hardware UDCs on a device, enabling the system to function as a USB peripheral. You can list its contents using ls /sys/class/udc/ to find the name of the UDC, such as 3f980000.usb , and then write that name to a gadget’s configuration to bind the gadget to the UDC.

Once the setup is complete, the folder structure and contents should resemble the example below, which sets up both a serial gadget and an Ethernet gadget on the same device:

ResearchGate-Raspberry-Pi-Single-Board-Computer- (8)

Now reboot, then connect the Raspberry Pi device to a host device (e.g. another Raspberry Pi, a Windows PC, or a Linux PC). The host should have a USB Ethernet device and a serial device attached.

Making it all work
All the commands described above need to be run every time the Raspberry Pi device starts up. Since Raspberry Pi OS uses systemd , that is the appropriate way to run the startup script that does all the setting up. Here is an example script that collates all the instructions from above:

ResearchGate-Raspberry-Pi-Single-Board-Computer- (9) ResearchGate-Raspberry-Pi-Single-Board-Computer- (10)

We now need to tell systemd to run our script on startup.
Създайте a file in /lib/systemd/system — the name you choose is up to you (as long as the suffix is .service ), but for this example, we will use mass-storage-device.service . Enter the following into the file (note that there are many different options for these service files; we’ve just used the ones we need):

ResearchGate-Raspberry-Pi-Single-Board-Computer- (11)

You will need to change the ExecStart line to point to wherever you have saved the setup script. You then need to tell systemd to run the service on startup:

ResearchGate-Raspberry-Pi-Single-Board-Computer- (12)

Now when you plug your Raspberry Pi into a host, it should appear as a mass storage device. You can disable the systemd service as follows:

ResearchGate-Raspberry-Pi-Single-Board-Computer- (13)

Attaching a login console to a serial port

If you have set up your Raspberry Pi as a serial gadget, you might want to use that serial gadget to log in to the device, rather than just using it for point-to-point serial communication. On the latest version of Raspberry Pi OS running systemd this is easy. You need to tell the system to create a getty on the serial port, and then tell systemd to start it up. The following sets up the getty on ttyGS0 (The tty created when using ConfigFS to set up a serial device); you may need to adjust this to match whichever tty the serial device is assigned to.

ResearchGate-Raspberry-Pi-Single-Board-Computer- (14)

This will start up the getty on the serial port and ensure it starts up automatically on each reboot.

съвет
What is a getty ? In Linux, a getty is a program that manages terminals (both physical serial ports and virtual consoles) to allow multiple users to log in to a system, handling tasks like initialising the terminal, displaying a login prompt, and invoking the login program to authenticate the user.

This feature can be particularly useful on something like a Raspberry Pi Zero or Raspberry Pi Zero 2 W. With just one USB connection providing both power and serial communication, you can plug in the device and log in to it via a terminal.

Заключение
For true USB gadget projects (e.g. Ethernet, serial, mass storage), the Raspberry Pi Zero family and Raspberry Pi Compute Modules are the best choice.
Raspberry Pi 4 and Raspberry Pi 5 do offer OTG support, but their power requirements may be an issue.
Raspberry Pi A, B, 2B, 3B and 3B+ boards do not support OTG.
If your project depends heavily on OTG, the best options are Raspberry Pi Zero 2 W or Raspberry Pi Compute Module 4 with the Compute Module 4 IO Board.
There are two options on the software side: the legacy system is still commonly used and is easy to set up; the ConfigFS system requires more work to set up but does provide better functionality.

Quick reference table

Модел OTG поддръжка Бележки
Raspberry Pi Zero / Zero W / Zero 2 W да Fully supported on USB data port
Raspberry Pi 4 Yes ¹ USB-C port in device mode
Raspberry Pi 5 Yes ¹ USB-C port in device mode
Raspberry Pi A/B/2B/3B/3B+ не Only host mode
Raspberry Pi Compute Module 1–3 да Exposed on OTG pins
Raspberry Pi Compute Module 4 да micro-USB on CM4 IO board

¹ Raspberry Pi 4 and 5 will usually draw power from the host via the USB cable, so there may be limitations on available current due to the higher power requirements of these devices.

Данни за контакт за повече информация
Моля, свържете се applications@raspberrypi.com if you have any queries about this whitepaper. Web: www.raspberrypi.com

Често задавани въпроси

What are the risks associated with enabling OTG mode?

Enabling OTG mode requires editing system files which may pose a risk if done incorrectly. It is recommended to follow the instructions carefully and back up important data before making changes.

Can I use OTG mode on Raspberry Pi models other than Zero, Zero W, and Zero 2 W?

While the instructions provided are specific to the mentioned models, you can explore similar configurations on other Raspberry Pi SBCs with appropriate adaptations.

Документи / Ресурси

ResearchGate Raspberry Pi Single Board Computer [pdf] Ръководство за употреба
Raspberry Pi Single Board Computer, Raspberry Pi, Single Board Computer, Board Computer, Computer

Референции

Оставете коментар

Вашият имейл адрес няма да бъде публикуван. Задължителните полета са маркирани *